问题描述:

I have to two data sets with different adapters inside a single activity and I want to use notifyDataSetChanged() however its not working for the other adapter. So inside my adapterFirst class I have LongCLickListener which is using notifyDataSetChanged() and I want to call the adapterSecond to notify too if adapterFirst is updated. The AdapterSecond data is not being updated when pressing LongClick

 public class AdapterFirst extends RecyclerView.Adapter <AdapterFirst .ViewHolder> {

private List<Object> objectList;

private Context mContext;

AdapterSecond adapterSecond;

public AdapteFirst(List<Object> list) { objectList= list; }

@Override

public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

View view = LayoutInflater.from(parent.getContext())

.inflate(R.layout.item_list, parent, false);

return new ViewHolder(view);

}

@Override

public void onBindViewHolder(final ViewHolder holder, int position) {

holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {

@Override

public boolean onLongClick(View v) {

//query method

notifyDataSetChanged(); //working

//here it gets the nullpointerexception error

adapterSecond = new AdapteSecond();

adapterSecond.notifyDataSetChanged();

}

});

}

@Override

public int getItemCount() {

return (objectList != null? objectList.size():0);

}

public class ViewHolder extends RecyclerView.ViewHolder {

public TextView data;

public ViewHolder(View itemView) {

super(itemView);

data= (TextView) itemView.findViewById(R.id.text);

}

}

}

AdapterSecond

 public class AdapterSecond extends

RecyclerView.Adapter <AdapterSecond.ViewHolder> {

private List<Object> objectList;

private Context mContext;

public AdapterSecond () {}

public AdapterSecond (List<Object> list) { objectList= list; }

@Override

public AdapterSecond.ViewHolder onCreateViewHolder(ViewGroup parent,

int viewType) {

View view = LayoutInflater.from(parent.getContext())

.inflate(R.layout.item_list_2, parent, false);

return new ViewHolder(view);

}

@Override

public void onBindViewHolder(final AdapterSecond.ViewHolder holder, int position) {

final Object object = objectList.get(holder.getAdapterPosition());

holder.data2.setText(object.getData());

}

@Override

public int getItemCount() {

return (objectList != null? objectList.size():0);

}

public class ViewHolder extends RecyclerView.ViewHolder {

public TextView data2;

public ViewHolder(View itemView) {

super(itemView);

data2= (TextView) itemView.findViewById(R.id.text2);

}

}

}

网友答案:

Seems like the order of initialization of the adapters have some issues.

Just make sure that you have initialize the secondAdapter before the firstAdapter

secondAdapter= new SecondAdapter();
firstAdapter = new FirstAdapter();

Just check the order in which they initialize!

相关阅读:
Top