-1

I get actionBar object below as null, and hence a NullPointerException when executing actionBar.setDisplayHomeAsUpEnabled(true). Following is my code which is called from onResume of the Fragment.

ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);

Followwing is the theme I apply to the activity in the onCreate:

 <style name="MyActionBarTheme" parent="Theme.AppCompat.Light">

        <item name="actionBarStyle">@style/MyActionBar</item>
        <item name="actionBarTabTextStyle">@style/MyActionBarTabText</item>
        <item name="actionMenuTextColor">@color/green</item>
        <item name="colorPrimary">@color/green</item>
        <item name="colorPrimaryDark">@color/greenD</item>

    </style>

My application has minimum api level set to 14. Please help me, explain why is the ActionBar object returned as null.

EDIT: getActivity().getActionBar(); returns null in Fragment.

Volodymyr Yatsykiv
  • 3,181
  • 1
  • 24
  • 28
Mayur More
  • 951
  • 2
  • 15
  • 37
  • Possible duplicate of [getActionBar() returns Null (AppCompat-v7 21)](http://stackoverflow.com/questions/26435231/getactionbar-returns-null-appcompat-v7-21) – Selvin Oct 16 '15 at 12:20
  • Possible duplicate of [getActionBar() returns null after SDK update to 5.0](http://stackoverflow.com/questions/26526564/getactionbar-returns-null-after-sdk-update-to-5-0) – Volodymyr Yatsykiv Oct 16 '15 at 12:20

2 Answers2

1

If you are using appCompat you need to use getSupportActionBar() instead of getActionBar()

dsharew
  • 10,377
  • 6
  • 49
  • 75
0

You need to use getSupportActionBar() when you use AppCompatActivity instead of getActionBar().

EDIT

When you use AppCompat theme you have to use AppCompatActivity.

Example code how to get ActionBar:

Activity activity = getActivity();
if(activity != null && activity instanceof AppCompatActivity) {
   AppCompatAcitivyt appCompatActivity = (AppCompatActivity) activity;
   ActionBar actionBar = appCompatActivity.getSupportActionBar();
   //your code
}
Volodymyr Yatsykiv
  • 3,181
  • 1
  • 24
  • 28
  • I am using it in a Fragment, not AppCompatActivity, and since my minimum version is 14, do I still need to use the support library? – Mayur More Oct 19 '15 at 05:33
  • it depends on your Activity that you use. But in any way, you use Theme.AppCompat.Light... so you have to use AppCompatActivity. – Volodymyr Yatsykiv Oct 19 '15 at 08:01