dotGitignore
dotGitignore

Reputation: 1627

Android Room - How to Add a TypeConverter

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.

Upvotes: 2

Views: 676

Answers (1)

John Joe
John Joe

Reputation: 12803

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.

Upvotes: 4

Related Questions