我有一个这样的实体类
@Entity
data class NewsResponse(
@PrimaryKey
@field:SerializedName("news")
val news: ArrayList<NewsItem?>? = null
)
NewsItem类就是这样
@Entity
data class NewsItem(
@field:SerializedName("imgUrl")
val imgUrl: String? = null,
@field:SerializedName("link")
val link: String? = null,
@field:SerializedName("description")
val description: String? = null,
@PrimaryKey
@field:SerializedName("title")
val title: String? = null
)
然后我有DAO这样的NewsResponse
@Dao
interface NewsRespDao {
@Query("SELECT * FROM NewsItem")
fun getNewsItems():LiveData<List<NewsItem>>
@Insert(onConflict = REPLACE)
fun insertNews(newsList: List<NewsItem?>?)
@Query("DELETE FROM NewsItem")
fun deleteAll()
}
我也有一个这样定义的TypeConverter
class NewsConverter {
@TypeConverter
fun fromString(value:String):ArrayList<NewsItem>{
val listType = object : TypeToken<ArrayList<NewsItem>>() {
}.type
return Gson().fromJson(value, listType)
}
fun fromArrayList(list:ArrayList<NewsItem>):String{
val gson = Gson()
return gson.toJson(list)
}
}
然后在RoomDatabase类中,我已经定义了这样的TypeConverter批注
@Database(entities = arrayOf(Source::class,NewsResponse::class),version = 1)
@TypeConverters(NewsConverter::class)
abstract class SourceDataBase : RoomDatabase(){
abstract fun sourceDao():SourceDao
companion object {
private var INSTANCE:SourceDataBase?=null
fun getInstance(context: Context):SourceDataBase?{
if(INSTANCE == null){
synchronized(SourceDataBase::class){
INSTANCE = Room.databaseBuilder(context.applicationContext,SourceDataBase::class.java,"source.db")
.build()
}
}
return INSTANCE
}
fun destroyInstance(){
INSTANCE=null
}
}
}
但是,每当我尝试运行时,都会出现一条错误消息
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
要保存对象列表,一种方法是定义TypeConverter,而我已经定义了它,但仍然出现错误。我在这里做错了什么?谢谢
答案 0 :(得分:2)
您不需要NewsConverter。您不需要将NewsResponse作为实体。 您的实体必须是这样的:
@Database(entities = arrayOf(Source::class,NewsItem::class),version = 1)
abstract class SourceDataBase : RoomDatabase(){
然后一切都应该正常工作