Search code examples
androidandroid-actionbar

Method invocation 'setTitle' may produce 'java.lang.NullpointerException'


I tried to set a title for an ActionBar with the following code:

@Override
public void onResume() {
    ((MainActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.artist));
    super.onResume();
}

but Android Studio shows me this warning:

Error warning

I searched on StackOverflow that it will be fixed by adding this code if(getSupportActionBar()!=null) in front of my code. But it causes an error in my script. I'm not sure how to fix this.


Solution

  • You have several options to do what you asked for:

    1 - Ignore the warning

    No need to explain further, this is not an error

    2 - The elegant solution

    Wrap your line with 'if' statement to make sure it's not null

    if(getSupportActionBar() != null) {
            getSupportActionBar().setTitle(getString(R.string.artist));
    }
    

    3 - Use assert

    assert getSupportActionBar() != null;
    getSupportActionBar().setTitle(getString(R.string.artist));
    

    4 - Move the warning

    If you use 'getSupportActionBar' in multiple locations, you can remove all of those warnings and in return you will only receive a warning on the @NonNull usage.

    @NonNull
    @Override
    public ActionBar getSupportActionBar() {
        return super.getSupportActionBar();
    }