简体   繁体   中英

Android Drawer Toggle

I've been trying to add this toggle for 5 hours. But it keeps telling be that the drawerLayout is null, which doesn't make any sense because it exists and I've been using it.

package com.example.android.musicalstructure;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {

    public final static int REQUEST_READ_EXTERNAL_STORAGE = 0;

    public View tempView;

    public String[] mActivitiesDrawer;
    public DrawerLayout drawerLayout;
    public ListView drawerList;
    public ActionBarDrawerToggle drawerToggle;


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

        instantiateDrawer();
        setDrawerOnClickListener(1);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        drawerToggle = new ActionBarDrawerToggle(MainActivity.this, drawerLayout, R.string.open_drawer, R.string.close_drawer) {
            public void onDrawerClosed(View view) {
                supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };

        if (drawerLayout != null) {
            Log.d("null", "it is not null");
            drawerLayout.addDrawerListener(drawerToggle);
            drawerToggle.syncState();
        }
    }

    public void instantiateDrawer() {

        mActivitiesDrawer = getResources().getStringArray(R.array.drawer_items);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerList = (ListView) findViewById(R.id.left_drawer);

        //Instantiating an adapter to manage the items for the ListView
        drawerList.setAdapter(new ArrayAdapter < String > (this,
            R.layout.drawer_list_item, mActivitiesDrawer));

    }

    public void setDrawerOnClickListener(final int activityNumber) {


        drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView <? > adapterView, View view, int i, long l) {
                setTempView(view);
                Log.d("activityNumber", activityNumber + "and i : " + i);
                if (i == activityNumber) {
                    return;
                } else if (i == 0) {
                    Intent intent = new Intent(getApplicationContext(), AllMusic.class);
                    startActivity(intent);
                } else if (i == 1) {
                    Intent intent = new Intent(getApplicationContext(), Trending.class);
                    startActivity(intent);
                } else if (i == 2) {
                    Intent intent = new Intent(getApplicationContext(), Albums.class);
                    startActivity(intent);
                } else if (i == 3) {
                    Intent intent = new Intent(getApplicationContext(), Playlists.class);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(getApplicationContext(), Trending.class);
                    startActivity(intent);
                }

            }
        });

    }

    public void getPermission() {
        int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {

            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                Toast toast = Toast.makeText(this, "Please accept the permission so the app can access you music files.", Toast.LENGTH_SHORT);
                toast.show();
                ActivityCompat.requestPermissions(this, new String[] {
                    Manifest.permission.READ_EXTERNAL_STORAGE
                }, REQUEST_READ_EXTERNAL_STORAGE);
            } else {
                ActivityCompat.requestPermissions(this, new String[] {
                    Manifest.permission.READ_EXTERNAL_STORAGE
                }, REQUEST_READ_EXTERNAL_STORAGE);
            }

        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

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

        return super.onOptionsItemSelected(item);
    }

    public void setTempView(View tempView) {
        this.tempView = tempView;
    }

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

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);
    }
}

and here is my drawer layout

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.android.musicalstructure.MainActivity">
<!-- The main content view -->
<FrameLayout
    android:id="@+id/content_frame"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<!-- The navigation drawer -->
<ListView
    android:id="@+id/left_drawer"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#111"/>
</android.support.v4.widget.DrawerLayout>

and here is the Error Log

07-29 16:45:01.211 14025-14025/com.example.android.musicalstructure E/AndroidRuntime: FATAL EXCEPTION: main

Process: com.example.android.musicalstructure, PID: 14025
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.musicalstructure/com.example.android.musicalstructure.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v4.widget.DrawerLayout.isDrawerOpen(int)' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.support.v4.widget.DrawerLayout.isDrawerOpen(int)' on a null object reference
at android.support.v7.app.ActionBarDrawerToggle.syncState(ActionBarDrawerToggle.java:239)
at com.example.android.musicalstructure.MainActivity.onPostCreate(MainActivity.java:150)
at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1188)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2398)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

can someone help me, and thanks :)

I found the solution, as I noticed from other answers. Most people messed up with assigning id's to the layouts. I using multiple activities with the drawer. My id's are right, the only problem is that I made a syntax mistake assigning the id's.

instead of writing

android:id="@+id/drawer_layout"

I wrote

android="@+id/drawer_layout"

and I corrected the same mistake in the other layouts.

If anyone faces this problem, just double check your Id's.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM