1
私は部屋の永続性ライブラリ経由でデータベースに値を保存しようとしています。私のSettingsValueModelConverter
が間違っているsomethingsがありません。どのように私はSettingsKeyContract
オブジェクトを最も良い方法で保存することができますか?Android room typeconverterの問題
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 }
}
解決しましたか? – crgarridos