0

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.

2
  • In selectedCardItems you save the indices of the items to be deleted? Commented Oct 21, 2018 at 13:32
  • Yes, it contains indices of the items to be deleted. Commented Oct 21, 2018 at 13:34

1 Answer 1

2

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() 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.