Android room persistent library – how to insert class that has a List object field

You can easly insert the class with list object field using TypeConverter and GSON,

public class DataConverter {

    @TypeConverter
    public String fromCountryLangList(List<CountryLang> countryLang) {
        if (countryLang == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        String json = gson.toJson(countryLang, type);
        return json;
    }

    @TypeConverter
    public List<CountryLang> toCountryLangList(String countryLangString) {
        if (countryLangString == null) {
            return (null);
        }
        Gson gson = new Gson();
        Type type = new TypeToken<List<CountryLang>>() {}.getType();
        List<CountryLang> countryLangList = gson.fromJson(countryLangString, type);
        return countryLangList;
    }
 }

Next, Add the @TypeConverters annotation to the AppDatabase class

    @Database(entities = {CountryModel.class}, version = 1)
    @TypeConverters({DataConverter.class})
    public abstract class AppDatabase extends RoomDatabase {
      public abstract CountriesDao countriesDao();
    }

For more information about TypeConverters in Room check our blog here and the official docs.

Leave a Comment