gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:54 25 4
gpt4 key购买 nike

我尝试通过房间持久性库将值保存到数据库。我的 SettingsValueModelConverter 有问题,缺少一些东西。如何以最佳方式保存 SettingsKeyContract 对象?

日志:

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 }

}

最佳答案

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

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

关于Android Room 无法弄清楚如何将此字段保存到数据库中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47633244/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com