Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 305
Navid Abutorab Avatar asked Oct 20 '25 02:10

Navid Abutorab


1 Answers

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

like image 77
Hadas Avatar answered Oct 21 '25 14:10

Hadas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!