0

I am pretty new to Android development and I am having the following project structure:

enter image description here

I would like to start my activity_category_list from the StoreViewHolder class of mine. That is, whenever a view is in the holder is clicked, category activity should start.

Here is my StoreViewHolder.java to achieve this:

public class StoreViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

    public TextView txtStoreName;
    public ImageView imageView;

    private ItemClickListener itemClickListener;

    public StoreViewHolder(View itemView) {
        super(itemView);

        txtStoreName = (TextView) itemView.findViewById(R.id.store_name);
        imageView = (ImageView) itemView.findViewById(R.id.store_image);

        itemView.setOnClickListener(this);
    }

    public void setItemClickListener(ItemClickListener itemClickListener) {
        this.itemClickListener = itemClickListener;
    }


    @Override
    public void onClick(View view) {
        itemClickListener.onClick(view, getAdapterPosition(), false);
        Intent categoryList = new Intent(view.getContext(), CategoryList.class);
        this.startActivity(categoryList); // does not compile here
    }
}

I get the titled error on the commented section. I tried various methods I have seen online but somehow none worked. Alternatively I also tried this but no luck:

 Intent categoryList = new Intent(StoreViewHolder.this, CategoryList.class);
 startActivity(categoryList);

Any thoughts?

Schütze
  • 1,044
  • 5
  • 28
  • 48

1 Answers1

0

To call startActivity(intent) you need context. Because startActivity(intent) method comes from Context class. In Activity you don't write like context.startActivity(intent); because Activity it self a Context as Acitivty extends Context. Pass Context in constructor and call context.startActivity(intent);

public class StoreViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

public TextView txtStoreName;
public ImageView imageView;
Context context;

private ItemClickListener itemClickListener;

public StoreViewHolder(View itemView, Context context) {
    super(itemView);
    this.context = context;
    txtStoreName = (TextView) itemView.findViewById(R.id.store_name);
    imageView = (ImageView) itemView.findViewById(R.id.store_image);

    itemView.setOnClickListener(this);
}

public void setItemClickListener(ItemClickListener itemClickListener) {
    this.itemClickListener = itemClickListener;
}


@Override
public void onClick(View view) {
    itemClickListener.onClick(view, getAdapterPosition(), false);
    Intent categoryList = new Intent(view.getContext(), CategoryList.class);
    context.startActivity(categoryList); // does not compile here
}
}

Similar question Calling startActivity() from outside of an Activity context

Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50