Home > database >  Remove duplicate items in list adapter
Remove duplicate items in list adapter

Time:11-29

I am new to Kotlin coding and I can't resolve this issue.

I have a Json list which looks like this :

[
  {
    "id": 01,
    "title": {
      "rendered": "MY TITLE 1"
    },
    "category": [52],

 
  },
 {
    "id": 02,
    "title": {
      "rendered": "MY TITLE 2"
    },
    "category": [52],[64]
  },
{
    "id": 03,
    "title": {
      "rendered": "MY TITLE 3"
    },
    "category": [64]
  }
...
]

I managed to code a list adapter with a recyclerview to display a list with each titles. Now I want another recyclerview with only each categories but all I can achieve is a list of categories with duplicates. I added a 'distinct()' to my list but I can't iterate it through the adapter.

Here is my code :

In the adapter :

 override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {
        val currentItem = mylist.flatMap { it.category}
        val list2 = currentItem.toList()
        val test = list2[position]
            holder.binding.txtCat.text =test.toString()
    }

The result in the emulator is: enter image description here

If I add a .distinct() to get rid of the duplicates like this :

 override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {
        val currentItem = mylist.flatMap { it.category}
        val list2 = currentItem.toList().distinct()
        val test = list2[position]
            holder.binding.txtCat.text =test.toString()
    }

I've got this error message : java.lang.IndexOutOfBoundsException: Index: 9, Size: 9

but if I change 'val test = list2[position]' to 'val test = list2', the result is :

enter image description here

Duplicated entries are removed but I cannot iterate it in the adapter ???

Thanks for your lights !

CodePudding user response:

Try to remove the duplicate values before creating your adapter. It's not a good idea to both editing your data set and traversing through it. Here you can find a way to remove duplicate values from your collection.

Why are you getting java.lang.IndexOutOfBoundsException? - Because you have created your adapter with data set with duplicate values (e.x. [1, 2, 3, 3, 3, 4, 5]) the adapter knows that 7 elements are present in the data set. Then you pass through this line of code val list2 = currentItem.toList().distinct() and your data set becomes [1, 2, 3, 4, 5]. There are no longer 7 items, but 5. The adapter doesn't know that and will still try to show 7 items. Thus, the IndexOutOfBoundsException exception.

CodePudding user response:

First of all, create distinct currentList from mylist.category

val currentItem = mylist.flatMap{it.category}.toList().distinct()

Then create your adapter based on currentItem list

override fun onBindViewHolder(holder: ListCatViewHolder, position: Int) {

        holder.binding.txtCat.text = currentItem[position].toString()

}
  • Related