Search code examples
javaandroidnullpointerexceptionandroid-actionbarandroid-toolbar

getSupportActionBar() NullPointerException


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?


Solution

  • 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
    }