Thursday 24 December 2015

Curious Case of RecyclerView


Sorry for the title as I was supposed to write Serious instead of Curious but no problem that will work too.

Assumptions :
1. Done with the most simplest implementation of the RecyclerView.
2. Provided options to each list item for deleting it.

So in this post we will not discuss about the RecyclerView implementation and adding options to add/delete item from it. 

We will be discussing about an issue that will occur for sure if implementation is not done with some care.

While implementation RecyclerView, there appears an inconsistency while adding and deleting items leading to an issue with addition and deletion of items from the list due to list not getting reset causing unchanged item indexes in the list.

A very frequent example of crash :
Delete second last item and then try deleting last item you will get crash due to IndexOutOfBoundsException.


Usually we add following line to remove an item from the RecylcerView

.....
mDataList.remove(position);
notifyItemRemoved(position);
.....


Possible Resolution : 
1. We can avoid this by simple calling notifyDataSetChanged() which resets the complete list but using this the added animation with item placement in event of addition or deletion. Also it is an expensive call in comparsion to notifyItemRemoved() or notifyItemInserted().

2. But to resolve this issue along with animation up, we need to add one more method call just below the above two method calls

.....
mDataList.remove(position);
notifyItemRemoved(position);
notifyItemRangeChanged(position, mDataList.size());
.....

It just resets the RecylerView and hence index of list items get updated.


More : 
1. Similar issue can also be seen when you add a new item to the RecyclerView at any position.
2. And in that case notifyItemInserted() is called and should be followed by notifyItemRangeChanged() .


Please comment in case of any clarifications.