0

I am trying to remove Items from adapter when Item is clicked The display is doing the right thing but when I click the last item, I get IndexOutOfBound Exception

my diff utils the below

class ItemListDiffUtilCallBack(val oldList: List<Item?>,
                                     val newList: List<Item?>) : DiffUtil.Callback() {

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean
            = oldList[oldItemPosition]?.Id == newList[newItemPosition]?.Id

    override fun getOldListSize() = oldList.size

    override fun getNewListSize() = newList.size

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean
            = oldList[oldItemPosition]?.isEnrolled == newList[newItemPosition]?.isEnrolled

    override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
        return super.getChangePayload(oldItemPosition, newItemPosition)
    }
}

this is how I'm updating the list where the newList have an Item removed from it.

The display is removing the Item with the default as intended

 private fun updateList(newList: MutableList<Item?>) {
        val oldList = itemList.toMutableList()
        itemList.clear()
        itemList.addAll(newList)
        val result = DiffUtil.calculateDiff(ItemListDiffUtilCallBack(oldList, itemList))
        result.dispatchUpdatesTo(this@ItemRecyclerViewAdapter)
    }

when the onBindViewHolder get trigger after dispatchUpdatesTo

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {

        if (holder is ItemViewHolder) {
            val Item = itemList[position] 
            holder.setItem(Item)

            val myButtonListener = View.OnClickListener {
                itemList[position]?.Id?.let { Id ->
                    listener.onItemClick(Id)
                }
            }
            holder.setButtonClickListener(myButtonListener )
        } 
    }

val Item = itemList[position] itemList still have the size before the update.

And when I click the last Item to remove it,

itemList[position]?.Id?.let { itemList[position] the position return the last Item of the old list so I get the IndexOutOfBound Exception

What did I do wrong ?

Anthony
  • 571
  • 1
  • 4
  • 20

1 Answers1

0

If you are deleting an item you have to submit a new list to your adapter. Your adapter has to inherit from :ListAdapter<T,K>(YourDiffcallback())

adapter.submitList(list)
Viatcheslav Ehrmann
  • 716
  • 2
  • 5
  • 11