45

My app is crashing the minute I run it after I changed my AppCompat-v7 to 21.0.0 and Compiled with no problem.

It gives me the error:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setIcon(int)' on a null object reference

on this line:

getActionBar().setIcon(R.drawable.ic_action_bar);

It works with AppCompat-v7 20.0.0, but not with 21.0.0.

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
user3184899
  • 3,019
  • 6
  • 30
  • 38

4 Answers4

87

You need to call getSupportActionBar() on an ActionBarActivity. Do not call getActionBar() -- that is not available on older devices, and for the new r21 edition of appcompat-v7, I would expect it to return null all the time, as the new ActionBarActivity disables and replaces the system action bar.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • in addition to this, you have to make sure toolbar is added into our layout and you are calling `setSupportActionBar(yourToolBar)` – Ankit Nov 24 '14 at 09:41
  • There is no getSupportActionBar in my ActionBarActivity – Roel Mar 24 '15 at 16:21
  • @DalvikVM: There should be: http://developer.android.com/reference/android/support/v7/app/ActionBarActivity.html#getSupportActionBar%28%29 – CommonsWare Mar 24 '15 at 16:39
  • @CommonsWare: sorry my mistake. I was looking at a fragment where I added my own `getActionbar()` which returned `this.getActivity().getActionBar()`. Notice that when you want to access it from a fragment you have to cast `getActivity()` to `ActionBarActivity`. – Roel Mar 25 '15 at 15:34
  • 1
    This would be a more complete answer: `((AppCompatActivity) getActivity()).getSupportActionBar().setIcon(R.drawable.ic_action_bar);` – Adrian Wreyford Mar 07 '16 at 12:47
11

If your activity is AppCompatActivity, you can get the action bar like this:

android.support.v7.app.ActionBar mActionBar = getSupportActionBar();
Ivo Stoyanov
  • 16,256
  • 8
  • 62
  • 65
2
Object actionBar = getSupportActionBar();

android.support.v7.internal.app.WindowDecorActionBar bar = (android.support.v7.internal.app.WindowDecorActionBar) actionBar;

If you are developing app targeting 21SDK but app is going to be used under older sdk's then this lines above are the solution.

You can't use getActionBar() under 21SDK when your activity extends ActionBarActivity

kamilws
  • 171
  • 1
  • 16
0

Replace ActionBar by android.support.v7.app.ActionBar in all you code. and use setSupportActionBar() also Extent your activity from AppCompatActivity. use android support v7 dependency.

Imran Khan
  • 158
  • 1
  • 3
  • 13