How to save enum field in the database room?

后端 未结 4 539
不思量自难忘°
不思量自难忘° 2020-12-10 11:47

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

Cannot figur

4条回答
  •  独厮守ぢ
    2020-12-10 11:56

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

    class Converters {
    
         @TypeConverter
         fun toHealth(value: String) = enumValueOf(value)
    
         @TypeConverter
         fun fromHealth(value: Health) = value.name
    }
    

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

    class Converters {
    
        @TypeConverter
        fun toHealth(value: Int) = enumValues()[value]
    
        @TypeConverter
        fun fromHealth(value: Health) = value.ordinal
    }
    

    Unfortunatally, there is no way to use generics Enum 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)
    

提交回复
热议问题