-11

I am getting a NullPointerException warning below at setDisplayHomeAsUpEnabled method.

if((getActivity()) != null) {
   if(((AppCompatActivity) getActivity()).getSupportActionBar() != null) {
((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false);
  }
 }

How do I fix this?

Vidhi Dave
  • 5,614
  • 2
  • 33
  • 55
Apper
  • 311
  • 1
  • 3
  • 10
  • Have you called `setSupportActionBar()` ? Post your Activity's theme . – ADM Feb 28 '18 at 09:53
  • 2
    Okay, I understand that when people see the word NullPointerException, there is a tendency to mark the question as duplicate immediately. I want to just point out that I have indeed read that post, and I have implemented the suggestions stated (i.e. in fact, this should be apparent from the code above that I have checked for the null exceptions). – Apper Feb 28 '18 at 09:56
  • 2
    You should probably fix your title. Something like "Suppress NPE Warning for getSupportActionBar()". And emphasize "warning" in the description. I myself had to read your question twice before I realized you weren't actually getting an Exception. – Mike M. Feb 28 '18 at 10:00
  • 2
    Right, I absolutely agree with your comment @MikeM. I don't know why I didn't realise this when I posted the question. Thanks! – Apper Feb 28 '18 at 10:02
  • There we go. Hopefully no more down votes haha. – Apper Feb 28 '18 at 10:06

2 Answers2

1

Because you don't put checks for NullPointerException ((AppCompatActivity) getActivity()).getSupportActionBar() gives actionbar object

but you are calling directly by

((AppCompatActivity) getActivity()).getSupportActionBar().setDisplayHomeAsUpEnabled(false)

that is why system gives warning for NullPointerException.

    if((getActivity()) != null) {
        ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
    }

Put above code. Your warning will remove.

Community
  • 1
  • 1
0
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);

Using toolbar is a preferred choice. If you use Toolbar and set the Actionbar, you don't need to chekc for NullPointerException.

  1. Probable cause is if you are trying to do this out of the Activity Context you will get NullpointerException. It must set within the Activity Context.

  2. Check your Manifest File, if you have set the theme as NoActionBar and trying to access Actionbar, change it to Apptheme.

Akshay
  • 318
  • 1
  • 15