8
public class VendorAdapter extends RecyclerView.Adapter<VendorAdapter.MyViewHolder> {

private List<Vendor> vendorList;


public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    public TextView name, rating, address;
    RelativeLayout rl;
    Context con;

    public MyViewHolder(View view) {
        super(view);
        name = (TextView) view.findViewById(R.id.tv1);
        address = (TextView) view.findViewById(R.id.tv2);
        rating = (TextView) view.findViewById(R.id.txtstar);
        rl=(RelativeLayout)view.findViewById(R.id.parentLayout);
        itemView.setClickable(true);
        itemView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent (v.getContext(), StartActivity.class);
         con.startActivity(intent);

    }
}


public VendorAdapter(List<Vendor> vendorList,Context con) {
    this.vendorList = vendorList;

}

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View itemView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.list_layout, parent, false);

    return new MyViewHolder(itemView);
}

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    Vendor movie = vendorList.get(position);
    /*holder.name.setText(movie.getTitle());
    holder.address.setText(movie.getGenre());
    holder.rating.setText(movie.getYear());*/
}

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

}

Unable to startActivity from Recycler View Adapter

I want to open same activity on every item click of recycler view,but the way i am doing it,i am getting NULL POINTER on this line-con.startActivity(intent); Please help me with this. ##

Siddharth Mishra
  • 340
  • 1
  • 4
  • 15

2 Answers2

24

You can use the context from the View you clicked on.

Intent intent = new Intent (v.getContext(), StartActivity.class);
v.getContext().startActivity(intent);

Or assign the context in your constructor

this.con = con;
Tom Sabel
  • 3,935
  • 33
  • 45
0

Move Context con; from MyViewHolder class to below VendorAdapter like this

public class VendorAdapter ...{
private List<Vendor> vendorList;
Context con; // move con to here

   public class MyViewHolder ...
    public TextView name, rating, address;
    RelativeLayout rl;
    ...
}

Then receive con in VendorAdapter constructor like this

public VendorAdapter(List<Vendor> vendorList,Context con) {
    this.vendorList = vendorList;
    this.con = con; // add this
}

Hope this help

Linh
  • 57,942
  • 23
  • 262
  • 279