如何修复 go to next activity in adapter (Context.getPackageName()' on a null object reference)

how to fix go to next activity in adapter (Context.getPackageName()' on a null object reference)


在我的项目中,我通过改造和制作适配器和模型
单击 cardview 转到下一个 activity 后出现问题,应用程序因错误而崩溃:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference
    at android.content.ComponentName.<init>(ComponentName.java:128)
    at android.content.Intent.<init>(Intent.java:5390)
    at ir.hmotamed.notline.adapter.NoteAdapter.onClick(NoteAdapter.java:54)
    at android.view.View.performClick(View.java:6261)

我的适配器代码:

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.notesViewHoler> {


List<Querynotes> querynotes;
private Context mContext;

public NoteAdapter(List<Querynotes> querynotes, MainActivity mainActivity){

    this.querynotes=querynotes;

}

@NonNull
@Override
public notesViewHoler onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.note_row,parent,false);
    return new notesViewHoler(view);

}

@Override
public void onBindViewHolder(@NonNull final notesViewHoler holder, int position) {

    final Querynotes queryPostses=querynotes.get(position);
    holder.title.setText(queryPostses.getTitle());
    holder.note.setText(queryPostses.getNote());
    holder.body.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent=new Intent(mContext,EditNoteActivity.class);
            intent.putExtra("nid",queryPostses.getId());
            intent.putExtra("ntitle",queryPostses.getTitle());
            intent.putExtra("ndesc",queryPostses.getNote());
            mContext.startActivity(intent);

        }
    });

}

@Override
public int getItemCount() {

    return querynotes.size();

}

public class notesViewHoler extends RecyclerView.ViewHolder{

    int id;
    CardView parent;
    TextView title;
    TextView note;
    RelativeLayout body;
    public notesViewHoler(View itemView) {
        super(itemView);
        parent=itemView.findViewById(R.id.rv_note_row);
        title=itemView.findViewById(R.id.tv_header_title);
        note=itemView.findViewById(R.id.tv_body_desc);
        body=itemView.findViewById(R.id.rv_row_body);

    }
}

我需要在点击我的项目后转到下一个 activity
但是在点击之后我的应用程序崩溃了,并且在第 54 行出现了我的适配器的错误
第 54 行是:

Intent intent=new Intent(mContext,EditNoteActivity.class);

您必须在使用前初始化您的context

public NoteAdapter(List<Querynotes> querynotes, MainActivity mainActivity){
mContext = mainActivity; \ add this line
    this.querynotes=querynotes;

}

您的上下文为空,因此发生了崩溃。确保像这样在适配器构造函数中传递上下文:

public NoteAdapter(List<Querynotes> querynotes, Context mContext){

    this.querynotes=querynotes;
    this.mContext=mContext;

}

并且在您要创建适配器的 activity 中:

NoteAdapter mNoteAdapter = new NoteAdapter(queryNotes, MainActivity.class);