Java android room类中的列表无法弄清楚如何将该字段保存到数据库中

时间:2019-05-10 12:14:16

标签: java android android-room

我无法在手机上安装应用程序,因为看到此错误:

  

错误:无法弄清楚如何将该字段保存到数据库中。您可以   考虑为其添加类型转换器。

发生这种情况是因为我在This课上学习:

@Entity(tableName = "last_state")
public class LastStateTable {

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    long id;
    @ColumnInfo(name = "date")
    String date;
    List<Icon> icon;
    }

    @Entity(tableName = "icon" )
    public class Icon {
        @PrimaryKey(autoGenerate = false)
        @ColumnInfo(name = "id")
        int id;
        @ColumnInfo(name = "nr")
        int nr;
        @ColumnInfo(name = "type")
        int type;
        @ColumnInfo(name = "value")
        int value;
    }

它无法安装在设备上,因为我也有一个列表?

我尝试这样做,但是有一些错误:

   public class Converters {
    @TypeConverter
    public static ArrayList<Icon> fromString(String value) {
        Type listType = new TypeToken<ArrayList<Icon>>() {}.getType();
        return new Gson().fromJson(value, listType);
    }

    @TypeConverter
    public static String fromArrayList(ArrayList<Icon> list) {
        Gson gson = new Gson();
        return gson.toJson(list);
    }
}

1 个答案:

答案 0 :(得分:0)

您可以添加类型转换器以指导会议室如何处理列表数据

类似这样的东西

/**
 * Type Converter to instruct Room how to serialize and deserialize List(s) of data
 */
public class ListConverter {

    private static Gson gson = new Gson();

    @TypeConverter
    public static List<Icon> stringToIconList(String data) {

        if (data == null) {
            return Collections.emptyList();
        }

        Type listType = new TypeToken<List<Icon>>() {}.getType();

        return gson.fromJson(data, listType);
    }


    @TypeConverter
    public static String iconListToString(List<Icon> list) {

        return gson.toJson(list);
    }
}

同样,您也必须为“房间”注释“图标”列表字段,以了解它是一个字段并知道要使用哪个转换器

@Entity(tableName = "last_state")
public class LastStateTable {

    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    long id;
    @ColumnInfo(name = "date")
    String date;
    @TypeConverters(ListConverter.class) // This is missing in your code
    @ColumnInfo(name = "icons") // This is missing in your code
    List<Icon> icon;
}

@Entity(tableName = "icon" )
public class Icon {
    @PrimaryKey(autoGenerate = false)
    @ColumnInfo(name = "id")
    int id;
    @ColumnInfo(name = "nr")
    int nr;
    @ColumnInfo(name = "type")
    int type;
    @ColumnInfo(name = "value")
    int value;
}

错误应该消失了

希望有帮助

欢呼