Home » Android » android – How to save enum field in the database room?

android – How to save enum field in the database room?

Posted by: admin June 15, 2020 Leave a comment


I must write the value from the enum enumeration to the database. An error occurs during compilation. What am I doing wrong?

Cannot figure out how to save this field into database. You can consider adding a type converter for it.

@ColumnInfo(name = "state_of_health")
var health: Health

enum class Health(val value: Int){

class HealthConverter{

    fun fromHealth(value: Health): Int{
        return value.ordinal

    fun toHealth(value: Int): Health{
        return when(value){
            -1 -> Health.NONE
            0 -> Health.VERY_BAD
            else -> Health.EXCELLENT

How to&Answers:

To fix this annotate your Database class with @TypeConverters annotation (and not your enum class).


@Database(entities = arrayOf(User::class), version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

Check https://developer.android.com/training/data-storage/room/referencing-data


You can make a convert to each enum, like this:

  fun toHealth(value: String) = enumValueOf<Health>(value)

  fun fromHealth(value: Health) = value.name

Or if you prefer store it as SQL integer, you can use ordinal too:

  fun toHealth(value: Int) = enumValues<Health>()[value]

  fun fromHealth(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.