Android Room - How to Add a TypeConverter

谁说我不能喝 提交于 2021-01-28 12:14:28

问题


I'm currently learning about the Room Persistence and I just want to ask on how to create a TypeConverter for a custom class?

Brand.kt

@Parcelize
@Entity(tableName = "brand")
data class Brand (
    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "name")
    val name: String
) : Parcelable

Product.kt

@Parcelize
@Entity(tableName = "product")
data class Product(
    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    val id: Int,

    @ColumnInfo(name = "brand")
    val brand: Brand, // This variable is my problem, I don't know how to fix it...

    @ColumnInfo(name = "name")
    val name: String,

    @ColumnInfo(name = "price")
    val price: Int
) : Parcelable

Right now I'm encountering an error and it says,

error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

and pointing to my Product class

I tried to put an annotation to my Product class like @TypeConverters(Brand.class) and still the error is popping, I really don't know what to do.

Any help is appreciated, Thanks.


回答1:


You can use @Embedded instead.

@Embedded
val brand: Brand,

From docs:-

Can be used as an annotation on a field of an Entity or Pojo to signal that nested fields (i.e. fields of the annotated field's class) can be referenced directly in the SQL queries.



来源:https://stackoverflow.com/questions/58296346/android-room-how-to-add-a-typeconverter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!