不支持将Kotlin密封类插入或检索到Room数据库中.枚举可以很容易地工作,但不是密封的类.下面是我的DOWNLOADSTATUS海豹示例
@Entity(tableName = "SomeTableName")
data class LibraryDownloadsEntity(
@PrimaryKey
val contentId: String,
val contentURI: String? = EMPTY_STRING,
val downloadDate: LocalDateTime? = null,
val downloadStatus: LibraryEntityDownloadStatus = LibraryEntityDownloadStatus.NOTDOWNLOADED()
)
// This is an sealed class
sealed class ShareLibraryEntityDownloadStatus {
class DOWNLOADING( val downloadProgress: Int) :
ShareLibraryEntityDownloadStatus()
class DOWNLOADED(val filePath: String) :
ShareLibraryEntityDownloadStatus()
class FAILED(val failureReason: DownloadFailureReason) :
ShareLibraryEntityDownloadStatus()
class NOTDOWNLOADED(): ShareLibraryEntityDownloadStatus()
}
在使用它时,我会得到如下编译时间错误
Cannot figure out how to save this field into database. You can consider adding a type converter for it. - downloadStatus in ... package
个
现在我使用了如下所示的类型转换器
// Converters for DownloadStatus
@TypeConverter
fun downloadStatusToString(downloadStatus: ShareLibraryEntityDownloadStatus): String {
return Gson().toJson(downloadStatus)
}
@TypeConverter
fun downloadStatusFromString(json: String): ShareLibraryEntityDownloadStatus {
return Gson().fromJson(json, ShareLibraryEntityDownloadStatus::class.java)
}
这应该是可行的,但您将在运行时记住以下错误:
java.lang.RuntimeException: Failed to invoke private "...somepackagename".downloads.LibraryEntityDownloadStatus() with no args
个
这说明密封类不能实例化是有道理的.关于如何将DownloadStatus信息存储到房间数据库有什么 idea 吗