0

Here is the code snippet in where Results data class contains list of objects:

@Entity(tableName = "objects_table")
data class Subscriber(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "object_id")
    var id: Int,
    @ColumnInfo(name = "object_name")
    var name: Results?,
    @ColumnInfo(name = "detected_time")
    var confidence: Results?

)

I tried Type converter but simililar error:

    @TypeConverter
fun restoreList(listOfString: String?): List<String?>? {
    return Gson().fromJson<List<String?>>(listOfString, object : TypeToken<List<String?>?>() {}.type)
}

@TypeConverter
fun saveList(listOfString: List<String?>?): String? {
    return Gson().toJson(listOfString)
}

The error is

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

Thanks in advance!

Nephes Dr
  • 21
  • 1
  • 5
  • Does this answer your question? [Android room persistent library - TypeConverter error of error: Cannot figure out how to save field to database"](https://stackoverflow.com/questions/44582397/android-room-persistent-library-typeconverter-error-of-error-cannot-figure-ou) – Ryan M Feb 25 '22 at 22:59

3 Answers3

0

the type converter needed is type converter for the "Results" class not the String list you did

Ramy Ibrahim
  • 656
  • 4
  • 19
0

Seems like you forgot to apply your TypeConverter class to your room database.

For example:

Database (note: you can have multiple TypeConverters)

@TypeConverters(
    value = [
        MyTypeConverters::class,
        MyOtherTypeConverters::class
    ]
) 
abstract class MyDatabase : RoomDatabase() {
    ...
}

TypeConverter

class MyTypeConverters {
    @TypeConverter
    fun restoreList(listOfString: String?): List<String?>? {
        return Gson().fromJson<List<String?>>(listOfString, object : TypeToken<List<String?>?>() {}.type)
    }

    @TypeConverter
    fun saveList(listOfString: List<String?>?): String? {
        return Gson().toJson(listOfString)
    }
}
D.Roters
  • 221
  • 2
  • 6
0

Add @Embedded annotation to your reference type variable.

Like that:

@Entity(tableName = "objects_table")
data class Subscriber(

    @PrimaryKey(autoGenerate = true)
    @ColumnInfo(name = "object_id")
    var id: Int,
    @Embedded(prefix = "name_")
    var name: Results?,
    @Embedded(prefix = "confidence_")
    var confidence: Results?
)
Yeldar Nurpeissov
  • 1,786
  • 14
  • 19