How to fix getActionBar method may produce java.lang.NullPointerException

Actually Android Studio isn’t showing you an “error message”, it’s just a warning.

Some answers propose the use of an assertion, Dalvik runtime has assertion turned off by default, so you have to actually turn it on for it to actually do something. In this case (assertion is turned off), what you’re essentially doing is just tricking Android Studio to not show you the warning. Also, I prefer not to use “assert” in production code.

In my opinion, what you should do is very simple.

if(getActionBar() != null){
   getActionBar().setDisplayHomeAsUpEnabled(true);
}

Update:
In case you’re using the support library version of the Action Bar, you should replace getActionBar() with getSupportActionBar().

if(getSupportActionBar() != null){
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

Leave a Comment