Search code examples
androidandroid-studioandroid-toolbar

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?


Solution

  • My suggestion is :- Not to check for null because Warnings are not Errors

    warning which you are talking about says "it may produce".It don't say 'will must produce'.

    But if you want to double sure you can check for null