如何修复适配器中的下一个活动(空对象引用上的Context.getPackageName()')

时间:2019-04-23 12:56:35

标签: android retrofit adapter


在我的项目中,我进行改造并制作适配器和模型
enter image description here 问题是点击cardview后转到下一个活动,应用程序因错误而崩溃:

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$1.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);

    }
}

我需要在单击我的项目后单击进入下一个活动
但是点击后,我的应用崩溃了,并且在我的适配器的第54行出现错误
第54行是:

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

2 个答案:

答案 0 :(得分:1)

使用前,您必须初始化context

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

}

答案 1 :(得分:0)

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

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

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

}

以及创建适配器的活动中:

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