Solution for RecyclerView — IndexOutOfBoundsException — Inconsistency detected

ElamParithi Arul
helloParithi
Published in
2 min readOct 21, 2019

Hey guys!

If you are working with recycler views on Android, you might be encountering this dreaded error: IndexOutOfBoundsException — Inconsistency detected. Invalid Item ## Item Position, etc. Let’s see a few ways to fix this.

Understand why this happens

When the user scrolls your recycler view while the data is being changed on the list (maybe because you are adding/removing elements in the background because of pull to refresh or because of pagination or some background sync process), the ViewHolder loses the reference to the item on the recycler view and the item on the data list.

Solutions

  1. Make sure you are finished with updating the data on the list and only then, on the main thread, notify the recycler view’s adapter using notifyDataSetChanged() .

2. If you are modifying the list using the .add() , addAll() , remove() , removeAll() , make the process is synchronized before notifying the recycler view’s adapter. (Or) Create a temporary list to contain your new data and set it directly to your main list attached to your adapter.

Example, if you are modifying your list like this :

val dataList : MutableList<Person> = listOf() // --> used by your recyclerview for showing the list
..
..
val personData = getPersons()
..
..
dataList.addAll(personData())
dataList.add(Person(name="Parithi"))
..
..
recyclerView.adapter?.notifyDataSetChanged()

Change the code into this :

val dataList : MutableList<Person> = listOf() // --> used by your recyclerview for showing the list
..
..
// create a temporary list
val temporaryList : MutableList<Person> = listOf()
val personData = getPersons()
..
..
temporaryList.addAll(personData())
temporaryList.add(Person(name="Parithi"))
..
..
dataList = temporaryList // set it to the main list
recyclerView.adapter?.notifyDataSetChanged()

Solutions that may work but not recommended — will affect UI experience

  1. Clear the recyclerview’s cache usingrecyclerView.getRecycledViewPool().clear();
  2. Disable the scrolling on the recycler view when the data is being updated by overriding the onTouch.

Hope this article, helped you fix the issue. Thanks for reading and Happy Coding :)

--

--

ElamParithi Arul
helloParithi

Loves to build beautiful products for the Internet.