In onCreate()
method of activity I have this code for ToolBar
:
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
My IDE warms me that getSupportActionBar().setDisplayHomeAsUpEnabled(true);
may produce NullPointerException
.
My question is should I ignore it and how can I fix it anyway?
The IDE warns you about a potential NullPointerException
because there are many cases where the app could throw one. For the example you could be using a NoActionBar theme for your whole Application
(or just for the concerned activity
), but still you're trying to retrieve a reference to the action bar using getActionBar()
(or getSupportActionBar()
).
Just ignore the warning, but keep in mind the notes above.
UPDATE:
You can get rid of the warning by explicitly checking for nullability:
toolbar = (Toolbar) findViewById(R.id.tool_bar);
if (toolbar != null) {
// you can safely invoke methods on the Toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
// Toolbar is null, handle it
}
You could check for null but if it is not crashing it should not be nessessary:
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Well both the answers are correct, but if you just want to remove the warning
ActionBar actionBar = getSupportActionBar();
assert actionBar != null;
actionBar.setDisplayHomeAsUpEnabled(true);
assert actionBar != null, says that ActionBar is not null, and so calling any method on this variable doesn't produce the warning of NullPointerException.
I guess it will work if you
assert getSupportActionBar() != null
But I'm not sure about that.
Above all answer given for escaping from NullPointerException,and after putting this in your code :-
if(getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Only solve exception issue after then also you will not get your toolbar null only. I want to say just check in your activity xml u have declared your toolbar or not,i think this will reslove your issue.
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar1"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" />
Just put toolbar in your activiy Xml.
来源:https://stackoverflow.com/questions/33982892/getsupportactionbar-nullpointerexception