Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
    )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading