Better Way to Get The Item Position in Android’s RecyclerView

Haydar Ali Ismail
2 min readDec 22, 2020

--

Most of the available applications today always have a screen where they show us a list of items. The main screen of WhatsApp provides us with a list of chat histories and contacts, Youtube provides us with a list of available videos, and so on. In Android, the most popular solution to provide users a list of items is by using RecyclerView. However, there is some issue regarding RecyclerView that I just discovered today.

The problem

Today, I’ve been stuck in a pretty serious problem regarding Recycler View. So, I have a list of items, let’s call it List<Post> posts. Then, I’ll initialize an adapter for it. Then we can set the adapter to a RecyclerView.

After quite some time, we might want to add, manipulate, or even delete some item from the list but still maintaining the same adapter. Naturally, we will use the notifyDataSetChanged or similar methods.

However, sometimes these methods are not executed properly. In my case, the posts list already updated, but the position value inside the OnBindViewHolder is not. That will be the problem when we need to use the actual position value to run some methods.

If you are sure you already notify the adapter the right way and still having an inconsistent items state in the adapter. You are coming to the right place.

If you are still quite confused of what’s the problem is about, you can check the similar problem here.

Why it is happening?

Apparently, when we run notifyItemRemoved, notifyItemInserted or any other similar methods, the adapter does not reinitialize the view and will not redraw it. It instead only removeS the unnecessary items or addS more new items without redrawing the whole view. Since it’s not redrawn there are some cases where the ViewHolder still holds the old position value before the data is manipulated. This old position value triggers the inconsistent item state problem.

The solution

Apparently, there is an easy solution for this problem. The RecyclerView.ViewHolder class provides us a method called getAdapterPosition which will return the proper position of anything that currently drawn on the RecyclerView. So, the way I fix the problem I had is by changing the position into viewHolder.getAdapterPosition().

…and it’s done. Now, the value of position should be consistent with the current data we have.

Wrap Up

It took me a few hours to notice this problem and the solution. So, I guess maybe if you stumbled upon this problem now you can save a few hours to do other things. Thank you for reading and happy coding!

--

--