Xarsiss Xarsiss - 1 year ago 120
Android Question

Unable to call method in Adapter from ViewHolder (RecyclerView)

I'm trying to delete an item from my RecyclerView when the user clicks on it. However, even though the delete method in the Adapter is public I get the error 'Cannot resolve method delete(int)' when trying to call 'delete' method from the onClick in MyViewHolder.

What gives? It's public so why can't I call it?

GroceryItemAdapter

public class GroceryItemAdapter extends RecyclerView.Adapter<MyViewHolder> {
private LayoutInflater inflater;
private Context context;

List<MetaData> data = Collections.emptyList();

public GroceryItemAdapter(Context context, List<MetaData> data) {
this.context = context;
inflater = LayoutInflater.from(context);
this.data = data;
}

public void delete(int position) {
data.remove(position);
notifyItemRemoved(position);
}


@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.grocery_item_row, parent, false);
MyViewHolder holder = new MyViewHolder(view);
Log.i("GroceryHero", "onCreateViewHolder called");

return holder;
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
MetaData current = data.get(position);
holder.title.setText(current.title);
holder.icon.setImageResource(current.iconid);
Log.i("GroceryHero","onBindViewHolder called " + position);
}

@Override
public int getItemCount() {
return data.size();
}

}


MyViewHolder:

class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView title;
ImageView icon;

public MyViewHolder(View itemView) {
super(itemView);
Log.i("GroceryHero", "MyViewHolder called");
title = (TextView) itemView.findViewById(R.id.grocery_text);
icon = (ImageView) itemView.findViewById(R.id.grocery_icon);
itemView.setOnClickListener(this);
}

@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Item clicked at " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
delete(getAdapterPosition()); // ERROR: Cannot resolve method
}
}

Answer Source

You're trying to call delete from the view holder class. But delete is a method of the adapter class. You can may be pass an instance of adapter to the view holder in onCreateViewHolder and store it as a private field.

GroceryItemAdapter mAdapter;
public MyViewHolder(View itemView, GroceryItemAdapter adapter) {
    mAdapter = adapter;
    ...
}

// now you can call
mAdapter.delete(getAdapterPosition());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download