74

I am using a toolbar as my actionbar in an activity. I am trying to add the method getActionBar().setDisplayHomeAsUpEnabled(true); to the Activity.java file for Up navigation for older devices.

The method produces the following error message in Android Studio:

Method invocation may produce java.lang.NullPointerException

The Up navigation on the toolbar works fine on newer devices...now I'm trying to figure out how to make sure it will work for older devices. Please advise.

From build.gradle:

dependencies {
   compile "com.android.support:appcompat-v7:22.1.0"
}

From AndroidManifest.xml:

android:theme="@style/Theme.AppCompat.NoActionBar.FullScreen" 

From styles.xml

<style name="Theme.AppCompat.NoActionBar.FullScreen" parent="AppTheme">
<item name="android:windowNoTitle">true</item>
<item name="windowActionBar">false</item>
<item name="android:windowFullscreen">true</item>

from Activity.java

public class CardViewActivity extends AppCompatActivity {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.cardviewinput);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    if (toolbar != null) {
        // Up navigation to the parent activity for 4.0 and earlier
        getActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.drawable.ic_action_previous_item);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
    }

}
mmBs
  • 8,421
  • 6
  • 38
  • 46
AJW
  • 1,578
  • 3
  • 36
  • 77

14 Answers14

128

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);
}
Community
  • 1
  • 1
Adam G
  • 1,527
  • 1
  • 12
  • 12
  • 2
    While I originally used assert to "solve" the warning, I agree that your recommended code is better than the assert hack. Answer has been upvoted and accepted. Note that I am using AppCompatActivity as a class so I must use getSupportActionBar() in my solution rather than the getActionBar() that you show above. – AJW Mar 03 '16 at 02:02
  • 4
    Why android studio not giving the same warning for other methods like getSupportActionBar().setTitle() ? – Piyush Kukadiya May 05 '17 at 06:30
  • I'm using the getSupportActionBar() != null but I am still thrown a null pointer on my toolbar. Does anyone know what is going on? I have tried the assert line, which also just throws a null pointer!??! What is going oN!??!?!?! – ZooMagic Mar 01 '18 at 09:51
  • @ZooMagic There are different reasons why it might throw a NPE. I advice you to search for other questions that are similar to yours or post your code on a new question. You need to share your layout file, manifest and Activity code. – Adam G Mar 01 '18 at 18:57
34

First off, you need to set the toolbar as the support ActionBar. Then if you're certain it's going to be there all the time, just assert it as != null. This will tell the compiler it won't be null, so the null check passes.

@Override
protected void onCreate(Bundle savedInstanceState)
{
   super.onCreate(savedInstanceState);
   setContentView(R.layout.cardviewinput);

   Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
   setSupportActionBar(toolbar);

   assert getSupportActionBar() != null;
   getSupportActionBar().setDisplayHomeAsUpEnabled(true); // it's getSupportActionBar() if you're using AppCompatActivity, not getActionBar()
}
Bogdan Zurac
  • 6,348
  • 11
  • 48
  • 96
  • Ok, looks good but the assert line generates a "Cannot resolve symbol 'getSupportActionBar'" error in Android Studio. Should it be "getSupportActionBar()" ? Please advise. – AJW Apr 23 '15 at 22:19
  • 1
    You can only access getSupportActionBar when extending AppCompatActivity or FragmentActivity – Sheychan Aug 05 '15 at 08:49
8

Thank You Andrew for your answer. If you have a Nav Drawer or something else that uses getSupportActionBar() you need to add assert getSupportActionBar() != null;

Peace,

Example:

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    assert getSupportActionBar() != null;
    getSupportActionBar().setTitle(mTitle);
}
Scott
  • 91
  • 1
  • 2
  • 3
    Is this valid for production, or only for testing? – gian1200 Apr 26 '15 at 01:22
  • gian1200 I am not sure. A good question. I was planning to release my app soon, so I will be doing research before I do the release... Thx. – Scott Apr 28 '15 at 00:05
  • My guess is that the compiler will change it to something like "if it is null, then throw an assertExeption"; not allowing you to handle the error. – gian1200 Apr 28 '15 at 00:15
4

Try this :

private ActionBar getActionBar() {
    return ((AppCompatActivity) getActivity()).getSupportActionBar();
}
Shubham A.
  • 2,446
  • 4
  • 36
  • 68
3

What I have done is override the getSupportActionBar() method in my base Activity and add a @NonNull annotation. This way, I only get one lint warning in the base activity about how I use @NonNull annotation for something that has a @Nullable annotation.

    @NonNull
    @Override
    public ActionBar getSupportActionBar() {
        // Small hack here so that Lint does not warn me in every single activity about null
        // action bar
        return super.getSupportActionBar();
    }
Catalin Morosan
  • 7,897
  • 11
  • 53
  • 73
  • thanks for your answer. I don't know about using lint. Can you comment on any advantage your answer has vs. Adam Ghani's answer up above? – AJW Apr 01 '16 at 02:14
  • With Adam's approach you have to write the if statement in all your activities. With my approach you just have to override the getSupportActionBar in the base activity and the rest of the code remains as before. – Catalin Morosan Apr 02 '16 at 05:32
3

I created a generic class such as:

public final class Cast
{
    private Cast() {}

    /**
     * Helps to eliminate annoying NullPointerException lint warning.
     */
    @android.support.annotation.NonNull
    public static <T> T neverNull(T value)
    {
        return value;
    }
}

then I can use it for any call with NullPointerException warning for which I am sure that it will never happen, e.g.

final ActionBar actionBar = Cast.neverNull(getSupportActionBar());
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);

P.S. don't forget to add "com.android.support:support-annotations" to your gradle file.

interrupt
  • 2,030
  • 17
  • 14
2

add assert getSupportActionBar() != null; before getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Nikos
  • 3,267
  • 1
  • 25
  • 32
Pankaj K Sharma
  • 240
  • 1
  • 12
0
 if(actionBar != null) {
  actionBar.setHomeButtonEnabled(true);
  actionBar.setBackgroundDrawable(ContextCompat.getDrawable(mContext,
                                  R.drawable.action_bar_gradient));
 }
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
Krishna
  • 1,556
  • 13
  • 21
0

use this theme: android:theme="@style/Theme.AppCompat.Light.NoActionBar"

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Title");
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setHomeAsUpIndicator(R.drawable.ic_action_previous_item);
actionBar.setDisplayHomeAsUpEnabled(true);
kirtan403
  • 7,293
  • 6
  • 54
  • 97
Surendran
  • 69
  • 1
  • 7
0

Alternatively you could assert actionbar to not null.Add the assertion before calling your actionbar as follows

assert getSupportActionBar() != null;

Final snippet would therefore look as follows:

    setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
    assert getSupportActionBar() != null;
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
RileyManda
  • 2,536
  • 25
  • 30
0

Try this :

setSupportActionBar (toolbar);
if(getSupportActionBar () != null) {
assert getSupportActionBar () != null;
getSupportActionBar ().setDisplayHomeUpEnabled(true);
}

Note that setSupportActionBar(toolbar) should be before getSupportActionBar().

saibhaskar
  • 435
  • 6
  • 21
0
  if(getSupportActionBar() != null){
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }
    OR

Replace the MainActivity extends AppCompatActivity to public class MainActivity extends AppCompatActivity

Robert
  • 5,278
  • 43
  • 65
  • 115
MEGHA DOBARIYA
  • 1,622
  • 9
  • 7
0

just check getSupportActionBar not equal to null

    setSupportActionBar(toolbar);

    if(getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("Daily Shopping List");
    }
0

If you are importing

android.app.ActionBar 

you have to use getActionBar()

and if you are importing

android.support.v7.app.ActionBar

use getSupportActionBar()

MN. Vala
  • 129
  • 1
  • 6