I have a list of items like the below that I would like to enter into a database using room.
data class MyRotasDayItem(
@PrimaryKey
@SerializedName("id")
val id: Long,
@SerializedName("date")
val date: String,
@Embedded
@SerializedName("dayEvents")
val dayEvents: List<SealedObj>
)
However I cant seem to add dayEvents. Even if I made the type List I get... Entities and POJOs must have a usable public constructor Do i have to use a type converter?
What if in the list Type is a Sealed class that contain other data objects like...
sealed class MySealedExample(
open val foo: Long,
open val bar: Long
) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
@Entity
data class AnExample1(
@Ignore override val foo: Long,
@Ignore override val bar: Long,
val something:String
) : MySealedExample(foo, bar)
@Entity
data class AnExample2(
@Ignore override val foo: Long,
@Ignore override val bar: Long,
val somethingElse:List<SomeObj>
) : MySealedExample(foo, bar)
}
Anyway to insert that into the database?
Thankyou
Use type converters You support custom types by providing type converters, which are methods that tell Room how to convert custom types to and from known types that Room can persist. You identify type converters by using the @TypeConverter annotation.
Sealed classes are used for representing restricted class hierarchies wherein the object or the value can have value only among one of the types, thus fixing your type hierarchies. Sealed classes are commonly used in cases, where you know what a given value to be only among a given set of options.
A sealed class, in C#, is a class that cannot be inherited by any class but can be instantiated. The design intent of a sealed class is to indicate that the class is specialized and there is no need to extend it to provide any additional functionality through inheritance to override its behavior.
Use type converters, I ran into a similar problem and fixed it using type converters. To convert sealed classes into string and vice versa, I used Gson extension from this gist.
@JvmStatic
@TypeConverter
fun sealedClassToString(sealedClass: SealedClass) : String = GsonExtension.toJson(sealedClass)
@JvmStatic
@TypeConverter
fun sealedClassFromString(sealedClass: String) : SealedClass = sealedClass.let { GsonExtension.fromJson(it) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With