user3184899
user3184899

Reputation: 3069

getActionBar() returns Null (AppCompat-v7 21)

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.

Upvotes: 45

Views: 39300

Answers (4)

Imran Khan
Imran Khan

Reputation: 158

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.

Upvotes: 0

Ivo Stoyanov
Ivo Stoyanov

Reputation: 18719

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

android.support.v7.app.ActionBar mActionBar = getSupportActionBar();

Upvotes: 11

kamilws
kamilws

Reputation: 171

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

Upvotes: 2

CommonsWare
CommonsWare

Reputation: 1006664

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.

Upvotes: 87

Related Questions