0

I have created a recycler view leaderboard adapter to display people names with their ranks. When I scroll down and up the serial no changes and it gets messed up. It's because the onBindViewHolder is being called again for the integer which sets the serial number.

How do I stop the method while scrolling? Is there any way?

Markus Kauppinen
  • 3,025
  • 4
  • 20
  • 30
Bitten Tech
  • 125
  • 1
  • 10
  • add your adapter code where is occur issue. –  Jul 06 '18 at 12:34
  • Your items are getting recycled. The default limit is 5. Try increasing the limit. Have a look at this https://stackoverflow.com/questions/42209168/how-to-make-recyclerview-stops-recycling-defined-positions – nimi0112 Jul 06 '18 at 13:27

1 Answers1

1

Your thinking is wrong here. onBindViewHolder is expected to be called when you scroll and you shouldn't try to stop it from being called.

The problem here is that you do the counting in onBindViewHolder. This is wrong. You are only supposed to bind the data to your views here, just as the method name implies. Don't change your data in onBindViewHolder and the problem will go away. Instead, prepare the data before sending it to the adapter.

Gennadii Saprykin
  • 4,505
  • 8
  • 31
  • 41
  • Exactly! onBindViewHolder should only be used for binding data to the already created views and not computation of data, since it is called every time a new item is scrolled into the view. You can refer to this answer for more in-depth explanation: https://stackoverflow.com/a/37524217/6726650 – Sudhanshu Vohra Jul 06 '18 at 13:22
  • So where should I do counting? Outside onBindViewHolder function? Where? – Bitten Tech Jul 06 '18 at 13:43
  • Yes, outside the adapter - 1) load the data and do the counting, 2) set data to the adapter 3) set the adapter to your `RecyclerView`. These steps are usually sufficient. Now, if for some reason you need to update the data again, you do 4) update the data and 5) call `notifyDataSetChanged` on the adapter instance. – Gennadii Saprykin Jul 06 '18 at 13:47
  • All data manipulations should happen where it's convenient for you, e.g. activity or fragment, but not in your adapter. Adapter is only a class that maps your data to the RecyclerView items. – Gennadii Saprykin Jul 06 '18 at 13:49