Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update single item in RecyclerView with DiffUtil

I'd like to update a single item in my RecyclerView. The item is just POJO bean that holds isFavourite flag. User can click on item and set/unset as favourite. I have implemented adater with DiffUtil callback. There is one callback method boolean areContentsTheSame (int oldItemPosition, int newItemPosition) but in my case old and new item is the same object so there is nothing to compare ( equals method returns true). Should I save previous flag value and then check for changes or is any simple solution?

like image 828
piotrpawlowski Avatar asked Sep 01 '17 22:09

piotrpawlowski


1 Answers

This is my solution. I don't use DiffUtil instead of I use notifyItemChanged(int position, Object payload). payload variable contains data that you want to update. Please refer below code:

public void updateMedication(MedicationRecord medication) {
    int index = mData.indexOf(medication);
    notifyItemChanged(index);

    Bundle diffPayLoad = new Bundle();
    diffPayLoad.putInt("notify", medication.getNotify());
    notifyItemChanged(index, diffPayLoad);
}

In RecyclerView.Adapter, add this function to handle the payload

@Override
public void onBindViewHolder(@NonNull SharedMedVH holder, 
                             int position, 
                             @NonNull List<Object> payloads) {
    if (payloads.isEmpty()) {
        super.onBindViewHolder(holder, position, payloads);
    } else {
        Bundle o = (Bundle) payloads.get(0);
        for (String key : o.keySet()) {
            if (key.equals("notify")) {
                holder.updateNotify(o.getInt("notify"));
            }
        }
    }
}
like image 142
Nam Pham Avatar answered Nov 12 '22 17:11

Nam Pham