binu j binu j - 5 months ago 25
Android Question

recyclerView ClickListener return null after notifyDataSetChanged()

i am using a recyclerView and loading the data from database.The recyclerView item have 2 buttons. The recyclerView loads fine and clicks work fine for the following code.

allData=db.getCatData(CATEGORYLIST_CIDD,1);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);


later i rearrange the adapter data for displaying the data in descending order by using this code

db=new DatabaseHandler(getActivity().getApplicationContext());
allData=db.getCatData(CATEGORYLIST_CIDD,order_id);
textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);
textlistadapter.notifyDataSetChanged();


Now the items are rearranged on the recyclerView, but the onShareButtonClickListener returns null, here is the code of the adapter.

private OnShareButtonClickListener onShareButtonClickListener;
public interface OnShareButtonClickListener {
void onItemClick(View view, Pojo obj, int position);
}
public void setOnShareButtonClickListener(final OnShareButtonClickListener onShareButtonClickListener) {
this.onShareButtonClickListener = onShareButtonClickListener;
}


the click listener code is here

holder.bt_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Snackbar.make(view, "Share Clicked", Snackbar.LENGTH_SHORT).show();
if (onShareButtonClickListener != null) {
onShareButtonClickListener.onItemClick(view, c, position);
}
}
});


The click does not work since the onShareButtonClickListener is null.

The same code works well for the first time and once i change the order then the click events are not working, all other functions are working well.

TWL TWL
Answer

you should only need to do this once:

textlistadapter = new TextListAdapter(getActivity(), allData);
recyclerView.setAdapter(textlistadapter);

later on, if you want to update/change the data, then you should do something like this:

textlistadapter.setListItems(allData);
textlistadapter.notifyDataSetChanged();

Where setListItems() is a public method in your adapter, an example like this:

public void setListItems(List<> allData) {
    this.data.clear();
    this.data.addAll(allData);
}