java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position: Android RecyclerView

Line of code which solve the issue:

myRecyclerViewReference.getRecycledViewPool().clear();

 

Understanding for issue:

This is the java.lang.IndexOutOfBoundsException which can be introduced in many scenarios with a improper coding for updating RecyclerView adapter or its item like: when if you try to change/insert/remove in adapter view item and at the same time you are trying to set new adapter.

Sometimes you found you are not able to reproduce this issue but it is coming inconsistently.

I have also encountered this issue with my flow let me tell you the flow in which I faced and then resolve it my self.

 

Scenario for issue: 

I have a list and list items are continuously get changed there state(I mean some new items are inserting by notifyItemInserted(@Position), some items are removed by notifyItemRemoved(@Position) ,  sometimes items are changed with new model data with notifyItemChanged(@Model) and along with this all notifyDataSetChanged and setAdapter (For new adapter set)  also get called in the same functional flow with some requirements.

I was not able to encounter where was the issue and then I do a thing is myRecyclerViewReference.getRecycledViewPool().clear(); I used this line of code before to the notifyDataSetChanged and new Adapter Instance initialization, that’s it now my issue get resolved.

According to me, things are happening is when new adapter was setting and in this mean time period single item related action (notifyItemChanged,notifyItemRemoved,notifyItemInserted) get executed then RecyclerView is not able to find out that pooled single item view holder to be notified in the new adapter item views and it results exception.

 

Solution for issue: 

Use myRecyclerViewReference.getRecycledViewPool().clear() before notifyDataSetChanged and new Adapter initialization to setAdapter

 

My Code:

rvLights.getRecycledViewPool().clear();
mLightAdapter = new LightAdapter(LightsActivity.this, mLightsList);
rvLights.setAdapter(mLightAdapter);
rvLights.getRecycledViewPool().clear();
mLightAdapter.notifyDataSetChanged();
//Do this trick with notifyItemChanged usages
if (mLightAdapter.getItemCount() > index) {
    mLightAdapter.notifyItemChanged(index);
}

//Do this trick with notifyItemRemoved usages
if (mLightAdapter.getItemCount() > index) {
 mLightAdapter.notifyItemRemoved(index);
}

***If this will not help then try by removing the item animation to the LayoutManager with respect to the RecyclerView (rvLights).

rvLights.setItemAnimator(null);

 

Comment if it will resolve your issue 🙂