Should I null check the getSupportActionBar() method even if earlier in that method I have set the support action bar using getSupportActionBar()?
In onCreate() I have the three lines
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));
Android Studio then gives me the warning
"Method invocation may produce java.lang.NullPointerException"
Assuming that the findViewById method does return a valid ToolBar object, do I still need to null check the getSupportActionBar() method or is it safe to just ignore the warning?
That may produce a NullPointer exception.
You have created a new Toolbar object, you can use toolbar.setTitle(getIntent().getStringExtra(TITLE_KEY)); to set the title. You'll need to do this before you call setSupportActionBar(toolbar);
There is no need to call getSupportActionBar(), since the actionbar that has been set is the toolbar. So you can directly use that object to edit your toolbar. That is faster than getSupportActionBar();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With