我有这样的模型
@Entity(tableName = "allrates")
class Data(
@ColumnInfo(name = "rates")
@SerializedName("rates")
@Expose
var rates: Map<String, Rates>,
@ColumnInfo(name = "start")
@SerializedName("start_at")
@Expose
var startDate: String,
@ColumnInfo(name = "end")
@SerializedName("end_at")
@Expose
var endDate: String,
@SerializedName("base")
@Expose
var base: String,
@PrimaryKey(autoGenerate = true)
var id: Int
)
我的问题是,当我尝试插入数据库时,没有显示任何错误,但是当我执行“ get”操作时,总是返回空值。大概是我的问题出在“转换器”上,但我不确定。
这是我的转换器
class mapConverter {
@TypeConverter
fun fromString(value: String): Map<String, Rates> {
val mapType = object : TypeToken<Map<String, Rates>>() {
}.type
return Gson().fromJson(value, mapType)
}
@TypeConverter
fun fromStringMap(map: Map<String, Rates>): String {
val gson = Gson()
return gson.toJson(map)
}
}
DAO在这里
@Dao
abstract class RatesDao {
@Query("SELECT * FROM allrates")
abstract fun loadRates(): LiveData<Data>
@Insert(onConflict = OnConflictStrategy.REPLACE)
abstract fun insertRates(rates: Data)
}
具有ROOM的Connexion
@Database(entities = [(Data::class)], version = 1, exportSchema = false)
@TypeConverters(mapConverter::class)
abstract class AppDatabase : RoomDatabase() {
companion object {
private var sInstance: AppDatabase? = null
private const val DATABASE_NAME: String = "RatesList"
fun getInstance(context: Context): AppDatabase {
if (sInstance == null) {
synchronized(AppDatabase::class) {
sInstance = Room.databaseBuilder(context.applicationContext,
AppDatabase::class.java, DATABASE_NAME)
.build()
}
}
return sInstance as AppDatabase
}
}
abstract fun ratesDao(): RatesDao
}
答案 0 :(得分:0)
您正在用Kotlin编写代码,因此请将此行 @JvmStatic 添加到mapConverter类
class mapConverter {
@JvmStatic
@TypeConverter
fun fromString(value: String): Map<String, Rates> {
val mapType = object : TypeToken<Map<String, Rates>>() {}.type
return Gson().fromJson(value, mapType)
}
@TypeConverter
@JvmStatic
fun fromStringMap(map: Map<String, Rates>): String {
val gson = Gson()
return gson.toJson(map)
}
}