Android - Method Invocation 'setOnClickListener' may Produce 'java.lang.Nullpointerexception'

Asked

Viewed 77 times

0

I’m new to Android. Android Studio always warns me about this but I don’t know what it means.

Method invocation 'setOnClickListener' may produce 'java.lang.NullPointerException'

I would like to understand better what it is and what the logic is to solve it. Thank you.

Here’s my mainactivity snippet

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Set the content of the activity to use the activity_main.xml layout file
        setContentView(R.layout.activity_main);

        //Listener Button for Family
        TextView family = (TextView) findViewById(R.id.family);
        family.setOnClickListener(new View.OnClickListener(){
            public void onClick(View view){
                Intent familyIntent = new Intent(MainActivity.this, FamilyActivity.class);
                startActivity(familyIntent);
            }
        });
    }
}

1 answer

0


It means that your Action in Textview can produce a null value error at runtime if it is initialized incorrectly.

Many people had this Warning using other components like Float Action Button (FAB). One simple way to solve is to check before setting an action (such as setOnClickListener, for example) if your textview can be null.

if (family != null) {
 family.setOnClickListener(new View.OnClickListener(){
        public void onClick(View view){
            Intent familyIntent = new Intent(MainActivity.this, FamilyActivity.class);
            startActivity(familyIntent);
        }
    });
 }
}
  • I was able to understand better now and saw that Android Studio suggests this automatic correction through Lint. Even so thank you Antonio!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.