How to store ArrayList of Enum in RoomDatabase

Enum:

public enum HelloEnum {
    A,
    B,
    C
}

Converter:

public class EnumConverter {

    @TypeConverter
    public List<HelloEnum> storedStringToEnum(String value) {
        List<String> dbValues = Arrays.asList(value.split("\\s*,\\s*"));
        List<HelloEnum> enums = new ArrayList<>();

        for (String s: dbValues)
            enums.add(HelloEnum.valueOf(s));

        return enums;
    }

    @TypeConverter
    public String languagesToStoredString(List<HelloEnum> cl) {
        String value = "";

        for (HelloEnum lang : cl)
            value += lang.name() + ",";

        return value;
    }    
}

In terms of inserting and fetching your data this will work not questions asked.

@Dao
public interface HelloPojoDao {

    @Query("SELECT * FROM helloPojo")
    List<HelloPojo> fetchAll();

    @Insert
    void insertPojo(HelloPojo pojo);
}

I would however point out that filtering by enum becomes a little more tricky now. For example if you want to write a query for fetching objects containing enum.A and enum.B, you will have to build a query that queries a string object for them. In this case "SELECT * FROM pojo WHERE enums contains ' A,' and ' B,'. As such it is better to assign number values to your enums (as @Kuffs answer details), as parsing ints will likely produce less issues than parsing strings.

Hope this resolves your issue. Feel free to ask any questions in the comment section, and happy hunting!


Ok using Kotlin is much simpler, when using name

class EnumTypeConverter {

    @TypeConverter
    fun restoreEnum(enumName: String): EnumType = EnumType.valueOf(enumName)

    @TypeConverter
    fun saveEnumToString(enumType: EnumType) = enumType.name
}