3

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.

plamut
  • 3,085
  • 10
  • 29
  • 40
Mhd Ridho Swasta
  • 117
  • 2
  • 15
  • you mean `if(((MainActivity) getActivity()).getSupportActionBar()!=null)` though you should use a callback mechanism – Pavneet_Singh Dec 09 '17 at 05:46
  • 1
    Possible duplicate of [Can getSupportActionBar be null right after setSupportActionBar?](https://stackoverflow.com/questions/31805899/can-getsupportactionbar-be-null-right-after-setsupportactionbar) – vinS Dec 09 '17 at 05:46
  • after i add 'if(((MainActivity) getActivity()).getSupportActionBar()!=null' inf front of my code the warn keep showing. – Mhd Ridho Swasta Dec 09 '17 at 05:52
  • setSupportActionBar(toolbar); write onCreate() in Main activity than you will right in your fragment ((MainActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.artist)); – Jackey kabra Dec 09 '17 at 06:07

1 Answers1

3

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();
}
Yogev Neumann
  • 2,099
  • 2
  • 13
  • 24