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

0

I'm new to Android. Android Studio always warns me about this but I do not know what it means.

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

I'd like to better understand what it's all about and what logic to solve it. Thank you.

Here is 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);
            }
        });
    }
}
    
asked by anonymous 10.01.2018 / 02:35

1 answer

0

It means that your Action in the TextView can produce a null value error at runtime if it is initialized in the wrong way.

Many people had this warning using other components like Float Action Button (FAB). A 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);
        }
    });
 }
}
    
10.01.2018 / 15:08