NullPointerException: with ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
Asked Answered
R

7

13

I get this nullPointerException on runtime:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference

code from mainActivity:

package com.example.vasilis.spangreek;

import android.app.ActionBar;
import android.app.Activity;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.util.DisplayMetrics;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ExpandableListView;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import adapter.ExpandableListViewAdapter;
import model.NavDrawerItem;


public class MainActivity extends Activity {

    private DrawerLayout mDrawerLayout;
    private ExpandableListView mExpandableListView;
    private ActionBarDrawerToggle mActionBarDrawerToggle;

    //nav drawer Title
    private CharSequence mDrawerTitle;

    //used to store app titles
    private CharSequence mTitles;

    //slide menu items
    private String[] navMenuItems;
    private String[] navSubMenuItems;
    private TypedArray  navMenuIcons;

    private List<NavDrawerItem> groupList;
    private List<NavDrawerItem> childList;
    private Map<NavDrawerItem, List<NavDrawerItem>> mapList;
    private ExpandableListViewAdapter mAdapter;
    ActionBar mActionBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitles = mDrawerTitle = getTitle();

        //nav drawer icons
        navMenuIcons = getResources().obtainTypedArray(R.array.nav_icons);

        mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);

        createGroupList();
        CreateChildList();

        // Recycle the typed array
        navMenuIcons.recycle();

        mExpandableListView = (ExpandableListView)findViewById(R.id.list_slideMenu);
        mAdapter = new ExpandableListViewAdapter(this, mapList, groupList);
        mExpandableListView.setAdapter(mAdapter);
        mActionBar = getActionBar();
        // enabling action bar app icon and behaving it as toggle button
        mActionBar.setDisplayHomeAsUpEnabled(true);
        mActionBar.setHomeButtonEnabled(true);

        //toggle
        mActionBarDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.string.app_name,   R.string.app_name) {

            public void onDrawerClosed(View drawerView) {
                mActionBar.setTitle(mDrawerTitle);

                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }


            public void onDrawerOpened(View drawerView) {
                mActionBar.setTitle(mDrawerTitle);
                // calling onPrepareOptionsMenu() to hide action bar icons
                invalidateOptionsMenu();
            }
        };

        mActionBarDrawerToggle.setHomeAsUpIndicator(R.drawable.ic_drawer);

        mDrawerLayout.setDrawerListener(mActionBarDrawerToggle);

        if(savedInstanceState == null) {
            //displayView(0);
        }


    }

    /***
     * Called when invalidateOptionsMenu() is triggered
     */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // if nav drawer is opened, hide the action items
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mExpandableListView);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitles = title;
        getActionBar().setTitle(mTitles);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        mActionBarDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mActionBarDrawerToggle  .onConfigurationChanged(newConfig);
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // toggle nav drawer on selecting action bar app icon/title
        if (mActionBarDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);

        }
    }

    private void createGroupList() {
        //load slide menu items
        navMenuItems = getResources().getStringArray(R.array.nav_items);

        groupList =new ArrayList<NavDrawerItem>();

        for (int i = 0 ; i <  navMenuItems.length ; i++ ) {
            groupList.add(i , new NavDrawerItem(navMenuItems[i], navMenuIcons.getResourceId(i, -1)));
        }
    }

    private void CreateChildList() {

        mapList = new LinkedHashMap<NavDrawerItem, List<NavDrawerItem>>();
        navSubMenuItems  = getResources().getStringArray(R.array.nav_sub_items);
        childList = new ArrayList<>();



        for ( NavDrawerItem item : groupList) {
            if(item.getTitle().equalsIgnoreCase("learning Spanish")) {
                for (int i = 0 ;  i < navSubMenuItems.length ; i ++) {
                    childList.add(i, new NavDrawerItem(navSubMenuItems[i]));
                }
            }

            mapList.put(item,childList);
        }

    }

    private void setGroupIndicatorToRight() {
        /* Get the screen width */
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;

        mExpandableListView.setIndicatorBounds(width - getDipsFromPixel(35), width
                - getDipsFromPixel(5));
    }

    // Convert pixel to dip
    public int getDipsFromPixel(float pixels) {
        // Get the screen's density scale
        final float scale = getResources().getDisplayMetrics().density;
        // Convert the dps to pixels, based on density scale
        return (int) (pixels * scale + 0.5f);
    }
}

the lines of code that have problem are :

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

i use : style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar"

I have used the getSupportActionBar() but i haven't fount any solution

Rigsdaler answered 6/6, 2015 at 10:49 Comment(4)
its because getActionBar(); is returning null.Champollion
is ur Activity extend ActionBarActivity ?Goodtempered
@Vasilisfoo Edit and paste complete code to figure out the problem.Alacrity
Your minSDK should 11 or higher then.Tohubohu
T
27

The cause of your issue is using MainActivity extend Activity with support theme style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar". It's incompatible things. Which min sdk you need?

In your code having MainActivity extends Activity you don't need AppCompatTheme. Use name="AppTheme" parent="android:Theme.Light"

If you are using Theme.AppCompat.Light.DarkActionBar, you should extend your Activity from AppCompatActivity, and use getSupportActionBar().

Instead of:

public class MainActivity extends Activity {

use:

public class MainActivity extends AppCompatActivity {

and instead of:

getActionBar().setTitle(mTitles);

use:

getSupportActionBar().setTitle(mTitles);
Torchwood answered 6/6, 2015 at 15:26 Comment(0)
T
3

This problem might be caused by your theme. Check it again, and make sure that it parent with Theme.AppCompat.Light.DarkActionBar.

<style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <item name="windowActionBar">true</item>
    ...
</style>

If your activity extends AppCompatActivity or ActionBarActivity, call getSupportActionBar().

Tohubohu answered 6/6, 2015 at 12:23 Comment(1)
I had the null pointer issue using getSupportActionBar(). My issue was fixed by adding <item name="windowActionBar">true</item> in my styles.xml.Blockus
O
1

Put assert getActionBar () != null; after mActionBar = getActionBar();

Oao answered 6/6, 2015 at 10:51 Comment(1)
Adding a null check hardly fixes the issue?Solander
G
0

In my case, I forgot to init my Toolbar, so, before using getSupportActionBar, I had to do this:

    appbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(appbar);

    getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_nav_menu);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Gregoriagregorian answered 20/8, 2016 at 3:15 Comment(0)
L
0

If you check this answer in 2019 like me , the problem is about your android manifest:

<application
android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

Check the documentation here:

https://developer.android.com/training/appbar/setting-up.html

You also take in mind the previous answer from TetianaDev:

Instead of:

public class MainActivity extends Activity {

use:

public class MainActivity extends AppCompatActivity {

and instead of:

getActionBar().setTitle(mTitles);

use:

getSupportActionBar().setTitle(mTitles);

This works for me.

Liverpool answered 1/4, 2019 at 9:41 Comment(0)
M
0

You should try this one. I think it will work.

    Toolbar toolbar = findViewById(R.id.toolbar1);
    setSupportActionBar(toolbar);

    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout = findViewById(R.id.drawer_layout);
    mDrawerLayout.setDrawerShadow(R.drawable.rectagle_with_black_outer,
            GravityCompat.START);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            toolbar, R.string.navigation_drawer_close,
            R.string.navigation_drawer_close) {
        public void onDrawerClosed(View view) {
            invalidateOptionsMenu();
        }

        public void onDrawerOpened(View drawerView) {
            invalidateOptionsMenu();
        }
    };
Mahayana answered 12/6, 2019 at 11:30 Comment(0)
U
0

This is clearly not the problem of OP, but other people may find it useful: for me the solution was to call setContentView(R.layout.activity_main) before the configuration of actionbar.

Unconcern answered 15/5, 2020 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.