I am new to android and got stuck when I click on an item in RecyclerView where the data set gets changed and position doesn't match with the ID in SQLite.I know we can get unique ID by using 'setHasStableID' but I was little confused as to where do I need to set this 'setHasStableId(true)' condition? How does this work?
The setHasStableIds(true) is to be applied to the adapter of RecylerView.
adapter.setHasStableIds(true);
Also for this to be taken effect you must have to override getItemId(int position), to return identified long for the item at position. We need to make sure there is no different item data with the same returned id. The id can be an id from the database which will be unique for each item and are not changed throughout.
//Inside the Adapter class
@Override
public long getItemId(int position) {
return itemList.get(position).getId();
}
This will reduce the blinking effect on dataset notify, where it modifies only items with changes.
And the great part is it will add cool animations on item position changes!.
To solve blinking issue, we need to reuse the same ViewHolder and view for the same item. because
- RecycleView disabled stable IDs by default.
- So generally after notifyDataSetChanged(), RecyclerView.Adapter didn’t assigned the same ViewHolder to original item in the data set.
So solution is :-
setHasStableIds(true) :-
- set
setHasStableIds(true);
in RecyclerView.Adapter . - true means this adapter would publish a unique value as a key for item in data set.
- Adapter can use the key to indicate they are the same one or not after notifying data changed.
override getItemId(int position) :-
Then we must override
getItemId(int position)
,to return identified long for the item at positionWe need to make sure there is no different item data with the same returned id.
For new readers:
Note that for the Paging 3.0 library stable IDs are unnecessary and therefore unsupported.
Reference: https://developer.android.com/reference/kotlin/androidx/paging/PagingDataAdapter#getitemid
© 2022 - 2024 — McMap. All rights reserved.