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!.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With