This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                3年前关闭。
            
                    
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();
}


}

无法从Recycler View Adapter启动Activity

我想在回收器视图的每个项目单击上打开相同的活动,但是我这样做的方式是,在此行con.startActivity(intent)上得到NULL POINTER;
请帮我解决一下这个。 ##

最佳答案

您可以从单击的视图中使用上下文。

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


或在构造函数中分配上下文

this.con = con;

07-27 23:11