Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store ArrayList of Enum in RoomDatabase

my Question is how to store

List<Enum>

in RoomDatabase, so far I find no answer for that.

like image 609
murt Avatar asked Jun 22 '17 11:06

murt


People also ask

How do I save an enum in my room database?

You can consider adding a type converter for it. Looks like you should annotate your Database class with @TypeConverters annotation (and not your enum class ). Check developer.android.com/training/data-storage/room/…

Can we have list in enum?

In Java 10 and later, you can conveniently create a non-modifiable List by passing the EnumSet . The order of the new list will be in the iterator order of the EnumSet . The iterator order of an EnumSet is the order in which the element objects of the enum were defined on that enum. Great insight in this answer!

How do I save an enum?

It isn't possible to store an enum in the user's defaults database. We need to convert the value to a type that is supported by the defaults system. The easiest solution is to ask the enum for its raw value and store that value in the user's defaults database.

Can enum be a list in C#?

The enum keyword in C# and . NET is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list. Usually, an enum is declared as public within a namespace and is available to all classes in the namespace.


1 Answers

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!

like image 52
Jack Dalton Avatar answered Nov 14 '22 23:11

Jack Dalton