Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The correct way of implementing getItemId() in RecyclerView.Adapter

I have generic class

public abstract class BaseAdapter<T> extends RecyclerView.Adapter {
  private List<T> itemsList = new ArrayList<>();
  //other override methods

  @Override
    public long getItemId(int position) {
        return position;
    }
}

What is the correct way to implementing getItemId()? I think that return position like in many example is not correct.

like image 209
Sky Avatar asked Mar 07 '17 11:03

Sky


People also ask

Which method must be overridden to implement a RecyclerView adapter?

Adapter. RecyclerView includes a new kind of adapter. It's a similar approach to the ones you already used, but with some peculiarities, such as a required ViewHolder . You will have to override two main methods: one to inflate the view and its view holder, and another one to bind data to the view.

What is getItemId?

The getItemId method is largely designed to work with Cursors that are backed by SQLite databases. It will return the underlying cursor's id field for the item in position 1.

What is ViewHolder in RecyclerView?

A ViewHolder describes an item view and metadata about its place within the RecyclerView. Adapter implementations should subclass ViewHolder and add fields for caching potentially expensive findViewById results. While LayoutParams belong to the LayoutManager , ViewHolders belong to the adapter.


2 Answers

  1. Create a base interface that has a method that returns a type long eg.

    interface BaseInterface{
        long getId(); 
    }
    
  2. Change

    abstract class BaseAdapter<T> extends RecyclerView.Adapter 
    

    to

    abstract class BaseAdapter<T extends BaseInterface> extends RecyclerView.Adapter {
    

    Note: The signature changed to T extends BaseInterface

  3. Replace

    @Override
    public long getItemId(int position) {
        return position;
    }
    

    with

    @Override
    public long getItemId(int position) {
        return itemsList.get(position).getId();
    }
    
like image 126
Bubunyo Nyavor Avatar answered Oct 02 '22 21:10

Bubunyo Nyavor


In the List you could only return the Id of the Item available at specific row as mentioned by Google documents:

getItemId

Get the row id associated with the specified position in the list.

But that's not the case with RecyclerView, in RecyclerView you have to ensure that you either return a unique Id for each Item or In case of no Stable Id you should return RecyclerView.NO_ID (-1). Please Refrain from returning values that are not stable. (An Stable value would be a unique value that does not change even if position of dataset changes)

like image 43
Keivan Esbati Avatar answered Oct 02 '22 22:10

Keivan Esbati