Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Your code is throwing on com.example.tabwithslidingdrawer.MainActivity.onCreate(MainActivity.java:95):

        // enabling action bar app icon and behaving it as toggle button
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

The problem is pretty simple- your Activity is inheriting from the new android.support.v7.app.ActionBarActivity. You should be using a call to getSupportActionBar() instead of getActionBar().

If you look above around line 65 of your code you'll see that you're already doing that:

        actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        // TODO: Remove the redundant calls to getSupportActionBar()
        //       and use variable actionBar instead
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

And then lower down around line 87 it looks like you figured out the same:

        getSupportActionBar().setTitle(
                        Html.fromHtml("<font color=\"black\">" + mTitle + " - "
                                        + menutitles[0] + "</font>"));
        // getActionBar().setTitle(mTitle +menutitles[0]);

Notice how you commented out getActionBar().


If anybody wants to use android.app.ActionBar and android.app.Activity you should change the app theme in styles.xml, for example:

<style name="AppTheme" parent="android:Theme.Holo.Light.DarkActionBar">

The problem is you could be using an AppCompat theme.

On the other hand, if you want to use android.support.v7.app.ActionBar and you extend your activity with AppCompatActivity then you must use an AppCompat theme to avoid this issue, for example:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Hope this helps.


when you extend appcompatActivity then use

this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and when you extend ActionBar then use

this.getActionBar().setDisplayHomeAsUpEnabled(true);

dont forget to call this function in oncreate after initializing the toolbar/actionbar

Tags:

Android