my Question is how to store
List<Enum>
in RoomDatabase, so far I find no answer for that.
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/…
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!
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With