1

I have created a FloatingActionButton object outside methods without giving it any value. Inside the method fabInitializer, I give it a value by referencing it to tag in the XML file. When I want to use a method of class's object I've created, Android Studio says:

object.method() may produce a java null pointer exception.

The program runs fine.

If the object value is null it should produce that message, but it is not. How can I fix this?

public void fabInitializer() {
    mFab = (FloatingActionButton) findViewById(R.id.fab);
    mFab.setOnClickListener(this);

}
Dan Getz
  • 8,774
  • 6
  • 30
  • 64
  • 1
    Hi, please also include the code for the layout XMLs - and it is also more helpful to paste the code text instead of a picture/screenshot. – ishmaelMakitla May 05 '16 at 17:53
  • 1
    As guys pointed out, you can ignore the warning. You can also suppress the warning by clicking ALT+ENTER on top of it and it'll provide you with options on how to 'fix' it. – Vucko May 06 '16 at 16:30

1 Answers1

3

This is just a warning. Android Studio cannot conclude that mFab isn't null (since it can be for various reasons). If you want to remove the warning and write code more defensively, add a defensive null check:

if (mFab!=null) mFab.setOnClickListener(this);
Community
  • 1
  • 1
nanofarad
  • 40,330
  • 4
  • 86
  • 117