无法弄清楚如何将该字段保存到数据库中,无法保存整数列表

时间:2018-09-07 18:13:39

标签: android kotlin android-room

我有这个实体:

@Entity(tableName = "recipes")
data class Recipe(
        @PrimaryKey val id: Int,
        val name: String,
        @TypeConverters(Converters::class)
        val categories: List<Int>,
        val picture: String,
        @Embedded(prefix = "time")
        val time: Time,
        val people: Int,
        val difficulty: Int,
        val price: Int,

        @Embedded(prefix = "ingredients")
        @TypeConverters(Converters::class)
        val ingredients: List<Ingredient>,

        @Embedded(prefix = "utensils")
        @TypeConverters(Converters::class)
        val utensils: List<Utensil>,

        @Embedded(prefix = "steps")
        @TypeConverters(Converters::class)
        val steps: List<Step>,

        val createdAt: String,
        val updatedAt: String
) : Serializable

当我编译它时,我得到了

Cannot figure out how to save this field into database. You can consider adding a type converter for it.
    private final java.util.List<java.lang.Integer> categories = null;

问题是,我添加了TypeConverter,它在我的类Converters中:

@TypeConverter
fun fromIntList(value: List<Int>): String {
    val gson = Gson()
    val type = object : TypeToken<List<Int>>() {}.type
    return gson.toJson(value, type)
}

@TypeConverter
fun toIntList(value: String): List<Int> {
    val gson = Gson()
    val type = object : TypeToken<List<Int>>() {}.type
    return gson.fromJson(value, type)
}

它应该工作,因为它知道应该将一个Int列表转换为字符串。 此外,我收到了这个错误,我不知道它可能从哪里来,我有5次这样的错误。

 Entities and Pojos must have a usable public constructor. You can have an empty
  constructor or a constructor whose parameters match the fields (by name and type).

我添加了嵌套类,例如Ingredients,Step,Ustensil,但我没有发布代码,因为它们不应该相关。

0 个答案:

没有答案