Skip to content
Advertisement

Why am I getting an error when trying to save a list in Room database with the help of a type converter?

I want to store a list of Integer type in a Room database. For this I wrote a converter that looks like:

public class TypeConverter {

static Gson gson = new Gson();

@androidx.room.TypeConverter
public static List<Integer> stringToIntegerList(String data) {
    if (data == null) {
        return Collections.emptyList();
    }

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

    return gson.fromJson(data, listType);
}

@androidx.room.TypeConverter
public static String someObjectListToString(List<Integer> someObjects) {
    return gson.toJson(someObjects);
}
}

Here is a part of the model class:

@TypeConverters(TypeConverter.class)
List<Integer> colors_ids;

And also a database class:

@Database(entities = {Flower.class}, version = 2)
@TypeConverters(TypeConverter.class)

And when I’m getting the list, I get an error:

Attempt to invoke interface method 'int java.util.List.size()' on a null object reference

So the list is null. What am I doing wrong? Thanks for any help.

EDIT:

This is how I save an array to Room database:

dao.insert(new Flower(something, something, ..., new ArrayList<Integer>(){{add(R.drawable.flower_clove_red); add(R.drawable.flower_clove_pink);}}));

Advertisement

Answer

The type converter class is alright. The problem was in my way of populating the database.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement