Navid Abutorab
Navid Abutorab

Reputation: 1787

android -room - saving object in room database

I've this json :

{
"products": [{
    "id": "150",
    "num": "7",
    "name": "450 SA"
}, {
    "id": "122",
    "num": "13",
    "name": "Gillette Blue"
}]}

I've created my models from it , i've these classes for it :

    @Entity
data class ProductsModel(
    @Json(name = "products")
    val products: List<Product>
)

@Entity
data class Product(
    @PrimaryKey(autoGenerate = false)
    val id: String,
    @Json(name = "name")
    val name: String,
    @Json(name = "num")
    val num: String,
)

this is my DAO class for inserting data into my room database :

@Dao
interface ProductsDAO {

// 2: Insert
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(product: ProductsModel)

When I want to run the application , I get this error :

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

How can I save these data into my database ?

Upvotes: 4

Views: 3097

Answers (1)

Hadas
Hadas

Reputation: 961

Room provides functionality for converting between primitive and boxed types but doesn't allow for object references between entities.

You can simply create a table that has 3 columns - id, name and num. So each row would be a different Product

OR

Your data base should only save the list of Product's and you should provide a TypeConverter, which converts a Product class to and from a known type that Room can persist.

more about type converters - link

Upvotes: 3

Related Questions