如何在数据库室中保存枚举字段? [英] How to save enum field in the database room?

查看:364
本文介绍了如何在数据库室中保存枚举字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须将enum枚举中的值写入数据库.编译期间发生错误.我在做什么错了?

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")
@TypeConverters(HealthConverter::class)
var health: Health

enum class Health(val value: Int){
    NONE(-1),
    VERY_BAD(0),
    ...
}

class HealthConverter{

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

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

}

推荐答案

要解决此问题,请使用@TypeConverters注释(而不是enum class)注释您的Database类.

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

示例:

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

检查 https://developer.android.com/training/数据存储/房间/引用数据

这篇关于如何在数据库室中保存枚举字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆