在房间数据库中插入项目列表时出现问题

问题描述 投票:0回答:1

我正在尝试从 API 获取新闻并尝试在数据库中插入文章列表。我从 API 获取列表大小 = 20,但数据库只有 1 行......仅插入文章列表中的最后一项。

下面的代码缺少什么?

DAO 房间:

@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
}
android android-room android-architecture-components
1个回答
0
投票

使用这个模型。您面临这个问题是因为您总是被告知将其插入到数据库的 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
    )
}
© www.soinside.com 2019 - 2024. All rights reserved.