我正在尝试将List<Object>
保存到Room数据库中。
我收到以下错误:
error: Cannot figure out how to save this field into database. You can consider adding a type converter for it.
private java.util.List<xxx.models.OBJECTX> carList;
房间实施:
@Entity(tableName = "nameOfTable")
class CachedObjectX(
@PrimaryKey
@ColumnInfo(name = "id") val id: Long,
@ColumnInfo(name = "list")
var carList: List<ObjectX>
)
@Dao
interface CachedObjectXDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(list: ArrayList<CachedObjectX>)
@Delete
fun delete(list: ArrayList<CachedObjectX>)
@Query("SELECT * FROM ...")
fun getAll(): ArrayList<CachedObjectX>
}
class CachedObjectXConverter {
companion object {
var gson = Gson()
@TypeConverter
@JvmStatic
fun toInsuredVehicle(json: String): List<ObjectX> {
val type = object : TypeToken<List<ObjectX>>() {}.type
return gson.fromJson(json, type)
}
@TypeConverter
@JvmStatic
fun toJson(torrent: List<ObjectX>): String {
val type = object: TypeToken<List<ObjectX>>() {}.type
return gson.toJson(torrent, type)
}
}
}
@Database(entities = [CachedObjectX::class], version = 1, exportSchema = false)
@TypeConverters(CachedObjectXConverter::class)
abstract class CachedObjectXDb : RoomDatabase() {
companion object {
private const val DB_NAME = "CachedObjectX.db"
val instance: CachedObjectXDb by lazy {
Room.databaseBuilder(
getContext(),
CCchedObjectXDb::class.java,
DB_NAME
).build()
}
}
abstract fun getDao(): CachedObjectXDao
}
有趣的是,我添加了TypeConverter
,但仍然会引发错误。我的实现有什么问题?刚开始是Room,所以很有可能出现问题。预先感谢。
答案 0 :(得分:0)
您还必须使ObjectX的pojo成为实体