Search code examples
androidkotlinandroid-room

Making sure that an itemview is only saved once (Kotlin)(Android)(Room)


I am unable to find a way to only save an Article only once, if a user were to save an article multiple times duplicates will appear, I need the saving process to only occur once.

enter image description here

//Note that the save button in the image above doesn't work on purpose, I am removing it in the future.

The image above is for reference.

NewsDetailActivity

override fun onCreate(savedInstanceState: Bundle?) {
    //Reference to an instance of the itemview in the recyclerview
   article = intent.getParcelableExtra("wholeArticle")
}



override fun onOptionsItemSelected(item: MenuItem): Boolean {
   when(item.itemId){
      R.id.save_news -> {
          article?.let { viewModel.saveArticle(it) }}
}

To keep things short, could someone advice or give me some resources to read, I can't seem to find any good ones thanks!

What I have tried

I have tried playing around with different logics and concepts, read through a couple of Articles and tried to reverse engineer other people's project, can't seem to understand how it works.


Solution

  • Check out this link, you will get an official Android Page where they have mentioned the purpose of onConflict in case of insertion.

    In your Dao Class,

    @Dao
    interface ArticleDao {
        @Insert(onConflict = OnConflictStrategy.REPLACE)
        fun insertSongs(varargs songs: Song)
    }
    

    However, there are other strategies too. (find_out) e.g. IGNORE, ABORT, FAIL, NONE, REPLACE, ROLLBACK