How To Save Enum Field In The Database Room?
Solution 1:
You can make a convert to each enum, like this:
classConverters{
@TypeConverterfuntoHealth(value: String) = enumValueOf<Health>(value)
@TypeConverterfunfromHealth(value: Health) = value.name
}
Or if you prefer store it as SQL integer, you can use ordinal too:
classConverters{
@TypeConverterfuntoHealth(value: Int) = enumValues<Health>()[value]
@TypeConverterfunfromHealth(value: Health) = value.ordinal
}
Unfortunatally, there is no way to use generics Enum<T> to accomplish this since unbound generics will raise an error Cannot use unbound generics in Type Converters.
Android Room team could seriously add an annotation and a generator for Enums to their kapt compiler.
Finally, annotate a database class, entity class, dao class, dao method, dao method parameter or entity field class with this:
@TypeConverters(Converters::class)Solution 2:
To fix this annotate your Database class with @TypeConverters annotation (and not your enum class).
Example:
@Database(entities = arrayOf(User::class), version = 1)
@TypeConverters(Converters::class)abstractclassAppDatabase : RoomDatabase() {
abstractfunuserDao(): UserDao
}
Check https://developer.android.com/training/data-storage/room/referencing-data
Solution 3:
This is no longer an issue in version 2.3.0-alpha4: "Room will now default to using an Enum to String and vice versa type converter if none is provided. If a type converter for an enum already exists, Room will prioritize using it over the default one."
"If a one-way type converter for reading already exists for the Enum, Room might accidentally use the built-in String to Enum converter which might not be desired. This is a known issue and can be fixed by making it a two-way converter."
Solution 4:
Enum class;
enumclassPriority {
HIGH,
MEDIUM,
LOW
}
Converter class;
classConverter{
@TypeConverterfunfromPriority(priority: Priority): String {
return priority.name
}
@TypeConverterfuntoPriority(priority: String): Priority {
return Priority.valueOf(priority)
}
}
usage;
@Database(entities = [MyData::class], version = 1, exportSchema = false)
@TypeConverters(Converter::class)
abstract class MyDatabase : RoomDatabase() {
// todo
}
Solution 5:
For java developers
The Enum
publicenumHealth {
NONE(-1),
VERY_BAD(0);
publicfinalint value;
Health(int newValue) {
value = newValue;
}
publicintgetValue(){
return value;
}
}
The type converter
publicclassHealthConverter {
/**
* Convert Health to an integer
*/
@TypeConverter
publicstaticintfromHealthToInt(Health value){
return value.ordinal();
}
/**
* Convert an integer to Health
*/
@TypeConverter
publicstatic Health fromIntToHealth(int value){
return (Health.values()[value]);
}
}
Post a Comment for "How To Save Enum Field In The Database Room?"