getSupportActionBar() NullPointerException

怎甘沉沦 提交于 2019-12-06 05:10:35

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!