0

I can not install an app on my phone because I see this error :

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

It happens because I have in class 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;
    }

It cannot install on the device because I have a List inside what I should too?

I try to do this but I have some errors :

   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);
    }
}
Darshan Jain
  • 781
  • 9
  • 19
kiki Kala2
  • 399
  • 5
  • 19

1 Answers1

0

You can add a Type Converter to instruct room on how to deal with the list data

Something like this

/**
 * 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);
    }
}

And also you have to annotate the Icon list field for Room too understand it is a field and to know what converter to use

@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;
}

And the error should be gone

Hope it helps

Cheers

Slobodan Antonijević
  • 2,533
  • 2
  • 17
  • 27