Taseer
Taseer

Reputation: 3502

Index out of bound: ArrayList

Problem

I have implemented multi-selection behavior for recycler view using an external library. Now, to remove items from recycler view, I implemented a two for loops. First for loop deleted items from SQLite and the second for loop removes correspondent views from the adapter. However, the problem arises when removing views from the adapter.

         for (i in selectedCardItems!!.indices)  //selectedCardItems stores selected card position.
            {
                val index = selectedCardItems!![i]
                val noteRowID = listItems!![index]  //list items contains references to items in SQLite and is fed to recyclerview.setadapter = myAdapter(context,listitems)


                dbHandler!!.deleteNote(noteRowID.noteID!!)
            }




            for(i in selectedCardItems!!.indices)
            {
                val index = selectedCardItems!![i]
                listItems!!.removeAt(i)  //problem starts here, due to mismatched indexes.

                adapter!!.notifyItemRemoved(i)
            }

            if(dbHandler!!.trashedNotesCount() == 0)
            {
                trashedRecyclerView!!.visibility = View.GONE
                emptyTrashImg!!.visibility = View.VISIBLE
                emptyTrashMsg!!.visibility = View.VISIBLE
            }

            selectedCardItems!!.clear()  //once all operation is done,remove card positions from this ArrayList.
        }

Both listitems and selectedCardPosition are of ArrayList type. I know that once an item from an ArrayList is removed from an index, then higher index item index is automatically moved to a lower index. What is an efficient way to fix this problem?

What I tried: A BAD fix is to basically remove the second for loop that removes views and replace it with adapter.notifyDataSetChanged() which is also removes deleting animations.

Upvotes: 0

Views: 70

Answers (1)

forpas
forpas

Reputation: 164089

If I understand your question correctly, the problem arises because deletions from the list ruin the initial indexing.If this is the case you have to start deletions from the higher index and then go down. So sort the list descending before the loop:

selectedCardItems!!.sortDescending() 

Upvotes: 2

Related Questions