wbk727
wbk727

Reputation: 8408

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>"));

Upvotes: 1

Views: 2165

Answers (1)

user_4685247
user_4685247

Reputation: 2995

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>"));
}

Upvotes: 3

Related Questions