我尝试将自定义类型保存在会议室数据库中。我总是遇到错误
错误:无法弄清楚如何将该字段保存到数据库中。您可以考虑为其添加类型转换器。
我为OutboxItemCache创建了转换器
我的实体
@Entity(tableName = "request")
class RequestCache(
@ColumnInfo(name = "requestId")
@PrimaryKey var id: String = "",
@TypeConverters(RequestConverter::class)
var outboxItemCache: OutboxItemCache)
我的RequestConverter
class RequestConverter {
companion object {
private val gson = Gson()
@TypeConverter
fun stringToOutboxItem(string: String): OutboxItemCache? {
if (TextUtils.isEmpty(string))
return null
return gson.fromJson(string, OutboxItemCache::class.java)
}
@TypeConverter
private fun outboxItemToString(outboxItem: OutboxItemCache): String {
return gson.toJson(outboxItem)
}
}
}
这是我的课程OutboxItemCache
class OutboxItemCache(
var id: String = "",
val numder: String,
date: String,
val headerDate: String,
name: String,
val certCount: String,
val status: String,
val statusColor: Int,
var statusInfo: String? = null,
val vetCertIds: List<String>
)
错误从未消失
答案 0 :(得分:0)
@Database(entities = {User.class}, version = 1)
@TypeConverters({RequestConverter.class})
public abstract class AppDatabase extends RoomDatabase {
public abstract UserDao userDao();
}
您需要将TypeConverters注册到数据库类。
编辑:
在科特林:
@Database(entities = arrayOf(User::class), version = 1)
@TypeConverters(RequestConverter::class)
abstract class AppDatabse : RoomDatabase() {
abstract fun userDAO(): UserDAO
}
这里唯一对您而言重要的代码行是
@TypeConverters(RequestConverter::class)
因为您应该已经拥有其他人。
编辑2:
尝试如下编写转换器类:
class RequestConverter {
@TypeConverter
fun stringToOutboxItem(string: String): OutboxItemCache? {
if (TextUtils.isEmpty(string))
return null
return Gson().fromJson(string, OutboxItemCache::class.java)
}
@TypeConverter
private fun outboxItemToString(outboxItem: OutboxItemCache): String {
return Gson().toJson(outboxItem)
}