Can getSupportActionBar be null right after setSupportActionBar?

Does Null need to check the getSupportActionBar() method, even if I installed the support action bar using getSupportActionBar() earlier in this method?

In onCreate() , I have three lines

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

Android Studio then gives me a warning

 "Method invocation may produce java.lang.NullPointerException" 

Assuming the findViewById method returns a valid ToolBar object, do I still need null to check the getSupportActionBar() method, or can I just ignore the warning?

+5
source share
4 answers

My suggestion: - Do not check for null since warnings are not errors

the warning you speak of says "he can produce." He does not say that he must produce.

But if you want to double confidence, you can check for null

+2
source

This may result in a NullPointer exception.

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

There is no need to call getSupportActionBar() , since the action bar that was installed is a toolbar. Thus, you can directly use this object to edit the toolbar. This is faster than getSupportActionBar ();

+2
source

To avoid this warning, you can always check if there is an ActionBar object.

 ActionBar mActionBar = getSupportActionBar(); if (mActionBar != null) { mActionBar.setTitle(getIntent().getStringExtra(TITLE_KEY)); } 
0
source

No, you should not ignore it. Because if the assumption is not fulfilled (for example, if findViewById(R.id.toolbar) starts to return null , because you are entering an error in another file in your project), you do want the NullPointerException to be thrown, so you can easily find the error when testing.

In other words: in my opinion, the best approach is unstable fast .

My code looks like this, with a comment that ignores the warning:

 //noinspection ConstantConditions: Action bar should always be present. If not, we prefer a NullPointerException here. getSupportActionBar().setHomeButtonEnabled(true); getSupportActionBar().setDisplayHomeAsUpEnabled(true); 
0
source

All Articles