Search code examples
javaandroidandroid-activityandroid-toolbar

Null pointer exception when setting title of toolbar widget


I'm trying to set a title for my toolbar widget, but after doing so the last line of my code becomes highlighted in yellow and I get a null pointer exception warning. What can be done to solve this issue?

Method invocation 'getSupportActionBar().setTitle(Html.fromHtml("" + getResources().getString(R.string.hello_world) + ""));' may produce 'java.lang.NullPointerException'

   Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(mToolbar);
   getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hello_world) + "</font>"));

Solution

  • The null pointer exception is only going to be thrown if the action bar would not be set. In your case it was merely a warning, there should be no error. However if you want to get rid of your warning try wrapping it with 'if' statement:

    if (getSupportActionBar() != null) {
        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        getSupportActionBar().setTitle(Html.fromHtml("<font color='#FFFFFF'>" + getResources().getString(R.string.hello_world) + "</font>"));
    }