Error in Navigation Drawer

2019-08-08 19:39发布

Somehow I am getting a null pointer Exception in this method

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    actionBarToggle.syncState();
}

actionBarToggle.syncState() in this there is a null pointer exception.

Now if I comment out this then there is null pointer exception when i touch the actionbar to open navigation drawer

    if (actionBarToggle.onOptionsItemSelected(item)) {
        return true;
    }

3条回答
Anthone
2楼-- · 2019-08-08 19:50

I found the problem actually I was doing this

        actionBarToggle = new ActionBarDrawerToggle(this, drawerLayout,
            R.drawable.ic_drawer, R.string.drawerOpen, R.string.drawerClose) {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle("Close");
            ActivityCompat.invalidateOptionsMenu(activity);
        }

        public void onDrawerOpened(View main) {
            getSupportActionBar().setTitle("Open");
            ActivityCompat.invalidateOptionsMenu(activity);
        }
    };
    drawerLayout.setDrawerListener(actionBarToggle); 
    drawerLayout = (DrawerLayout) findViewById(R.id.navigationDrawer);//This should be    before actionBarToggle

So I was intailizing the drawerLayout after using it in actionBarToggle.

查看更多
你好瞎i
3楼-- · 2019-08-08 20:05

I also had NullPointerException. That was a silly mistake, I was doing:

drawerToggle = new ActionBarDrawerToggle(this,
            drawerLayout,
            R.drawable.ic_drawer,
            1,
            2){ ... }

I hardcoded those two strings for accesibility by saying 1,2, because I found those strings unimportant. As far as I was running Android 2.3-4.3 everything was ok, but on 4.4 I was getting an exception. Solution is simple: just create those two strings in values/strings.xml

Sorry for my english :)

查看更多
淡お忘
4楼-- · 2019-08-08 20:11

Follow the instructions here.

http://developer.android.com/training/implementing-navigation/nav-drawer.html

Your actionBarToggle object is null. Create the ActionBarDrawerToggle and assign it to your variable before you try to use it.

查看更多
登录 后发表回答