There is no default support for inserting or retreiving kotlin sealed classes into the ROOM database. Enums could be easily work, but not SEALED classes. Below is my example for a DOWNLOADSTATUS seal
@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()
}
Upon using it I will get compile time error as below
Cannot figure out how to save this field into database. You can consider adding a type converter for it. - downloadStatus in ... package
Now I used a typeconverter as below
// 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)
}
This should work but then you will rember this error on runtime :
java.lang.RuntimeException: Failed to invoke private "...somepackagename".downloads.LibraryEntityDownloadStatus() with no args
This make sense that sealed class can't be instantiated. Any idea on how to store downloadStatus information into room db