Xarsiss Xarsiss - 2 years ago 140
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?


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) {

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;

public void onBindViewHolder(MyViewHolder holder, int position) {
MetaData current = data.get(position);
Log.i("GroceryHero","onBindViewHolder called " + position);

public int getItemCount() {
return data.size();



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

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

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download