2

im saving an entity that looks like this

@Entity
data class Entity(
    @PrimaryKey val id: Int,
    val productPresentationList: List<Int>,
    val supplierComparePriceList: List<SupplierComparePrice>
)

And, when I run the app i got this error message

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected an int but was BEGIN_OBJECT at line 1 column 3 path $[0]
        at com.google.gson.Gson.fromJson(Gson.java:975)
        at com.google.gson.Gson.fromJson(Gson.java:928)
        at com.google.gson.Gson.fromJson(Gson.java:877)
        at com.yopdev.wabi2b.db.Converters.restoreProductPresentation(Converters.kt:162)
        at com.yopdev.wabi2b.db.dao.CartDao_Impl$6.call(CartDao_Impl.java:281)
        at com.yopdev.wabi2b.db.dao.CartDao_Impl$6.call(CartDao_Impl.java:262)
        at androidx.room.CoroutinesRoom$Companion$createFlow$1$1$1.invokeSuspend(CoroutinesRoom.kt:128)
        at kotlin.coroutines.jvm.internal.BaseContinuationImpl.resumeWith(ContinuationImpl.kt:33)
        at kotlinx.coroutines.DispatchedTask.run(DispatchedTask.kt:106)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)

So, after that i tried to use a converter like this

   @TypeConverter
    fun restoreProductPresentation(listOfString: String): List<Int> =
        Gson().fromJson(listOfString, object : TypeToken<List<Int>>() {}.type)

    @TypeConverter
    fun saveProductPresentation(list: List<Int>): String =
        Gson().toJson(list)

Unfortunately, that didn“t work either.

How can i achieve this ?

Edward
  • 5,942
  • 4
  • 38
  • 55
Nicote Ool
  • 121
  • 8

1 Answers1

1

You cannot directly have a column as a list/array. However you can have a column that stores a converted list/array by using a 'holder' object along with a TypeConverter.

So you could, for example, have :-

data class MyListHolder(
    val myList: List<Int>
)

And then have the Entity :-

@Entity
data class Entity(
    @PrimaryKey val id: Int,
    val productPresentationList: MyListHolder,
    val supplierComparePriceList: List<SupplierComparePrice>
)

along with TypeConverters that convert the List into types that are acceptable for Entities. Typically a JSON String e.g.

@TypeConverter
fun fromMyListHolder(mlh: MyListHolder): String {
    return Gson().toJson(mlh)
}
@TypeConverter
fun toStatesHolder(mlh: String): MyListHolder {
    return Gson().fromJson(mlh,MyListHolder::class.java)
}

Note. that as you have val supplierComparePriceList: List<SupplierComparePrice> then you would need to approach this in a similar way.

MikeT
  • 51,415
  • 16
  • 49
  • 68