Search code examples
androidandroid-roomandroid-architecture-components

issue with inserting list of items in Room data base


I am trying to fetch news from API and trying to insert list of articles in Database. I am getting list size = 20 from API but database has only 1 row....inserting only last item from the list of articles.

What is missing in below code?

Room DAO:

@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertArticles(newsLocal: List<NewsLocal>?)

Repository:

suspend fun refreshArticles(category: String) {
    val articles = apiService.getTopHeadlines()
    withContext(Dispatchers.IO) {
        newsDao.insertArticles(articles.toLocalNewsList())
    }
}

Model Mapper:

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
}

Solution

  • Use this model. this you face this issue becoz you are always tell that insert that in 0 potion on the db. i assume that id is you primary key and also auto increment.

    NewsLocal(
        publishedAt = this.publishedAt,
        author = this.author,
        urlToImage = this.urlToImage,
        description = this.description,
        source = sourceObj,
        title = this.title,
        url = this.url,
        content = this.content
        )
    }