简体   繁体   中英

Click recyclerView new activity Error Attempt to invoke virtual method

I need help, for onclick on recyclerview and open new actity, im clicked in item list close app and logcat error is: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference

My code:

 @Override
public void onBindViewHolder(final estadoView estadoView, final int i) {
    final Estado estado = estadoList.get(i);
    estadoView.txtnombreMostrar.setText(estado.getStateName());



   estadoView.txtnombreMostrar.setOnClickListener(new View.OnClickListener() {

       @Override
       public void onClick(View v) {
           Intent intent =  new Intent(context, Invernadero.class);
           context.startActivity(intent);
       } });


}

And my public class is:

public class estadoView extends RecyclerView.ViewHolder {
    private TextView  txtnombreMostrar;

    RelativeLayout parentLayout;


    public estadoView(@NonNull View itemView) {
    super(itemView);
    txtnombreMostrar = itemView.findViewById(R.id.txtNombreMostrar);

    }

}

whats is the problem? Im search in web, in forums, but im not solve my problem

Code在此处输入图像描述

LogCat在此处输入图像描述

context is null, how to solved? 在此处输入图像描述

It seems that you've a context issue, but as you didn't provide how did you get the context, for now replace it in your view listener with v.getContext() as below:

 @Override
public void onBindViewHolder(final estadoView estadoView, final int i) {
    final Estado estado = estadoList.get(i);
    estadoView.txtnombreMostrar.setText(estado.getStateName());



   estadoView.txtnombreMostrar.setOnClickListener(new View.OnClickListener() {

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


}

check your context when start a new Intent, where you get the context, maybe the context still null or not assigned yet

java.lang.String android.content.Context.getPackageName()

i'm sure the context is null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM