问题
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?
回答1:
My suggestion is :- Not to check for null because Warnings are not Errors
warning which you are talking about says "it may produce".It don't say 'will must produce'.
But if you want to double sure you can check for null
回答2:
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();
回答3:
To avoid having this warning you can always check if the ActionBar
object is null.
ActionBar mActionBar = getSupportActionBar();
if (mActionBar != null) {
mActionBar.setTitle(getIntent().getStringExtra(TITLE_KEY));
}
回答4:
No, you should not null check this. Because if the assumption fails (for example if findViewById(R.id.toolbar)
starts returning null
because you introduce a bug in another file in your project), you do want a NullPointerException to be thrown, so you easily find the error when you test.
In other words: In my opinion, the best approach is to fail fast.
My code looks like this, with a comment that silence the warning:
//noinspection ConstantConditions: Action bar should always be present. If not, we prefer a NullPointerException here.
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
来源:https://stackoverflow.com/questions/31805899/can-getsupportactionbar-be-null-right-after-setsupportactionbar