AJW
AJW

Reputation: 1649

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

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();
            }
        });
    }

}

Upvotes: 74

Views: 64496

Answers (14)

MN. Vala
MN. Vala

Reputation: 149

If you are importing

android.app.ActionBar 

you have to use getActionBar()

and if you are importing

android.support.v7.app.ActionBar

use getSupportActionBar()

Upvotes: 0

Salahuddin
Salahuddin

Reputation: 1

just check getSupportActionBar not equal to null

    setSupportActionBar(toolbar);

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

Upvotes: 0

MEGHA RAMOLIYA
MEGHA RAMOLIYA

Reputation: 1927

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

Replace the MainActivity extends AppCompatActivity to public class MainActivity extends AppCompatActivity

Upvotes: 0

saibhaskar
saibhaskar

Reputation: 467

Try this :

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

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

Upvotes: 0

RileyManda
RileyManda

Reputation: 2651

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);

Upvotes: 0

Surendran
Surendran

Reputation: 69

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);

Upvotes: 0

Krishna
Krishna

Reputation: 1634

 if(actionBar != null) {
  actionBar.setHomeButtonEnabled(true);
  actionBar.setBackgroundDrawable(ContextCompat.getDrawable(mContext,
                                  R.drawable.action_bar_gradient));
 }

Upvotes: 0

interrupt
interrupt

Reputation: 2070

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.

Upvotes: 3

Catalin Morosan
Catalin Morosan

Reputation: 7937

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();
    }

Upvotes: 3

Adam G
Adam G

Reputation: 1527

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);
}

Upvotes: 128

Pankaj K Sharma
Pankaj K Sharma

Reputation: 230

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

Upvotes: 2

Shubham A.
Shubham A.

Reputation: 2534

Try this :

private ActionBar getActionBar() {
    return ((AppCompatActivity) getActivity()).getSupportActionBar();
}

Upvotes: 4

Bogdan Zurac
Bogdan Zurac

Reputation: 6451

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()
}

Upvotes: 34

Scott
Scott

Reputation: 91

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);
}

Upvotes: 8

Related Questions