-2

Lately Android Studio has started showing me unnecessary NPE warnings for views in onCreate. The app compiles and runs properly but it's quite distracting, for instance, when the whole textView.setOnClickListener block is highlighted in yellow.
Annotations should prevent this but is there a way to do it globally from the settings without affecting the other NPE warnings?

Code sample here:

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

    setContentView(R.layout.activity_main);

    TextView label = (TextView) findViewById(R.id.label);

    label.setOnClickListener(new View.OnClickListener() { //NPE warning for this
        @Override
        public void onClick(View v) {
           // code here
        }
    });
}
goat
  • 307
  • 3
  • 8

1 Answers1

2

NullPointerException is thrown when an application attempts to use an object reference, having the null value. These include: Calling an instance method on the object referred by a null reference.

  1. You are missing to set setContentView(R.layout.put_your_xml);

Basically what this function does is display the Layout created thorugh XML or the Dynamically created layout view in the Screen.

Finally

  @Override
   public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.put_your_xml);// You missing this
    TextView label = (TextView) findViewById(R.id.label);

    label.setOnClickListener(new View.OnClickListener() { //NPE warning for this
        @Override
        public void onClick(View v) {
           // code here
        }
    });
}
IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198