Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can getSupportActionBar be null right after setSupportActionBar?

Should I null check the getSupportActionBar() method even if earlier in that method I have set the support action bar using getSupportActionBar()?

In onCreate() I have the three lines

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));

Android Studio then gives me the warning

"Method invocation may produce java.lang.NullPointerException"

Assuming that the findViewById method does return a valid ToolBar object, do I still need to null check the getSupportActionBar() method or is it safe to just ignore the warning?

like image 618
MungoRae Avatar asked Aug 04 '15 09:08

MungoRae


1 Answers

That may produce a NullPointer exception.

You have created a new Toolbar object, you can use toolbar.setTitle(getIntent().getStringExtra(TITLE_KEY)); to set the title. You'll need to do this before you call setSupportActionBar(toolbar);

There is no need to call getSupportActionBar(), since the actionbar that has been set is the toolbar. So you can directly use that object to edit your toolbar. That is faster than getSupportActionBar();

like image 186
tim687 Avatar answered Oct 13 '22 20:10

tim687