Android Room无法弄清楚如何将此字段保存到数据库中

时间:2017-12-04 12:19:02

标签: android kotlin typeconverter android-room

我正尝试通过房间持久性库将保存值用于数据库。我的SettingsValueModelConverter错误的东西是错的。如何以最佳方式保存SettingsKeyContract个对象?

logcat的:

SettingsModel

Error:(14, 1) error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.

代码:

object SETTING_CONS{
    const val TABLE = "Content_Setting"
    const val ID    = "uid"
    const val KEY   = "key"
    const val VALUE = "value"
}

class SettingsValueModel(var value: SettingsKeyContract)
class SettingsValueModelConverter {

    @TypeConverter
    fun fromString(value: String): SettingsKeyContract = Gson().fromJson(value, object : TypeToken<SettingsKeyContract>() {}.type)

    @TypeConverter
    fun fromModel(value: SettingsKeyContract): String = Gson().toJson(value)

}

@Entity(tableName = SETTING_CONS.TABLE)
class SettingsModel(@ColumnInfo(name = SETTING_CONS.KEY) @SETTINGS var key: String,
                    @ColumnInfo(name = SETTING_CONS.VALUE) var value: SettingsValueModel) {

    @ColumnInfo(name = SETTING_CONS.ID)
    @PrimaryKey(autoGenerate = true)
    var uid: Int = 0

}

@Dao
interface SettingsDao {

    @Query("SELECT * FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.ID} = :key")
    fun get(@SETTINGS key: String): LiveData<SettingsModel>

    @get:Query("SELECT * FROM ${SETTING_CONS.TABLE}")
    val all: LiveData<MutableList<SettingsModel>>

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insert(model: SettingsModel): Long

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    fun insertAll(vararg models: SettingsModel): LongArray

    @Query("DELETE FROM ${SETTING_CONS.TABLE} WHERE ${SETTING_CONS.KEY} = :key")
    fun delete(@SETTINGS key: String)

    @Query("DELETE FROM ${SETTING_CONS.TABLE}")
    fun clear()

}


interface SettingsKeyContract { val key: String }
interface TypeSettingsKeyContract<out T : Any> : SettingsKeyContract { val default: T }

sealed class SETTING(override val key: String) : SettingsKeyContract {

    object FIRST_LAUNCH_DATE : SETTING("first_launch_date"), TypeSettingsKeyContract<Long> { override val default = 0L }

}

1 个答案:

答案 0 :(得分:4)

您在哪里定义数据库? 您应该可以选择指定要使用的转换器,例如:

@Database(entities = arrayOf(SettingsModel::class) , version = 1, exportSchema = false)
@TypeConverters(SettingsValueModelConverter::class)
abstract class AppDatabase: RoomDatabase() {
    abstract fun SettingsDao(): SettingsDao
}