房间和装修:List <Object>

时间:2019-11-20 15:20:23

标签: android kotlin retrofit2 android-room dao

我想将我的新闻保存在会议室数据库中。当响应上的数据是新闻列表时,但当它是包含新闻列表的新闻列表时,我不知道该怎么做。

这是我的代码: 我的API Get函数:

@GET("other/club.json")
suspend fun getListNews(): Response<NewsList>

我的模特:

data class NewsList(
@SerializedName(value = "news")
val news: List<News>)

@Entity(tableName = "news_table")
data class News(
@PrimaryKey(autoGenerate = false)
@SerializedName(value = "id")
var id: Int,

@SerializedName(value = "type")
var type: String,

@SerializedName(value = "date")
var date: String,

@SerializedName(value = "title")
var title: String,

@SerializedName(value = "picture")
var picture: String,

@SerializedName(value = "content")
var content: String)

我的DAO:

@Dao
interface NewsDao {

@Insert
fun insert(news: News)

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertAll(news: NewsList)

@Update
fun update(news: News)

@Delete
fun delete(news: News)

@Query("DELETE FROM news_table")
fun deleteAllNews()

@Query("SELECT * FROM news_table")
fun getAllNews(): LiveData<NewsList>
}

来自API的响应:

"news": [
{
"nid": 1,
"type": "one",
 ...
},
{
"nid": 2,
"type": "two",
 ...
}
]

我的数据库:

@Database(
entities = [News::class],
version = 1,
exportSchema = false
)
abstract class NewsDatabase : RoomDatabase() {

//--- DAO ---///
abstract fun newsDao(): NewsDao

companion object{
    @Volatile private var instance: NewsDatabase? = null

    fun getInstance(context: Context): NewsDatabase {
        return instance ?: synchronized(this) {
            instance ?: buildDatabase(context).also { instance = it }
        }
    }

    private fun buildDatabase(context: Context) =
        Room.databaseBuilder(context.applicationContext, NewsDatabase::class.java, "test.db")
            .build()
}
}

我听说过TypeConverters,但是请使用此示例的最佳方法是什么?

0 个答案:

没有答案