我正在尝试从 API 获取新闻并尝试在数据库中插入文章列表。我从 API 获取列表大小 = 20,但数据库只有 1 行......仅插入文章列表中的最后一项。
下面的代码缺少什么?
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertArticles(newsLocal: List<NewsLocal>?)
suspend fun refreshArticles(category: String) {
val articles = apiService.getTopHeadlines()
withContext(Dispatchers.IO) {
newsDao.insertArticles(articles.toLocalNewsList())
}
}
fun NewsRemote.ArticlesItem.toLocalNews(): NewsLocal {
val sourceObj = Source(
sourceId = this.source?.id ?: "",
name = this.source?.name ?: ""
)
return NewsLocal(
id = 0,
publishedAt = this.publishedAt,
author = this.author,
urlToImage = this.urlToImage,
description = this.description,
source = sourceObj,
title = this.title,
url = this.url,
content = this.content
)
}
fun NewsRemote.toLocalNewsList(): List<NewsLocal> {
val newsLocalList: MutableList<NewsLocal> = mutableListOf()
this.articles?.forEach { articleItem ->
if (articleItem != null) {
val localNews = articleItem.toLocalNews()
newsLocalList.add(localNews)
}
}
return newsLocalList
}
使用这个模型。您面临这个问题是因为您总是被告知将其插入到数据库的 0 部分中。我假设 id 是你的主键并且也是自动递增的。
NewsLocal(
publishedAt = this.publishedAt,
author = this.author,
urlToImage = this.urlToImage,
description = this.description,
source = sourceObj,
title = this.title,
url = this.url,
content = this.content
)
}