空指针异常 DrawerLayout

Null pointer exception DrawerLayout

这是我的 MainActivity.java

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MainActivity extends AppCompatActivity {

ListView mNavigationDrawer;


private Toolbar mToolbar;
private ActionBarDrawerToggle mDrawerToggle;
 DrawerLayout mDrawerLayout;

private boolean mUserLearnedDrawer;
private boolean mFromSavedInstanceState;

public static final String PREF_FILE_NAME = "pref";
public static final String KEY_USER_LEARNED_DRAWER = "user_learned_drawer";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        mFromSavedInstanceState = true;
    }
    mToolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(mToolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

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

    mNavigationDrawer = (ListView) findViewById(R.id.navigation_drawer);
    mNavigationDrawer.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.navigation_drawer_list)));

    setDrawers(mDrawerLayout, mToolbar);
}

@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) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
public void setDrawers(DrawerLayout drawerLayout, Toolbar toolbar) {
    mDrawerLayout = drawerLayout;
    mToolbar = toolbar;
    mDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close) {
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            if (!mUserLearnedDrawer)
                mUserLearnedDrawer = true;
            saveToPreference(getApplicationContext(), KEY_USER_LEARNED_DRAWER, mUserLearnedDrawer + "");
//                getActivity().invalidateOptionsMenu();

        }

        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
//                getActivity().invalidateOptionsMenu();
        }

        @Override
        public void onDrawerSlide(View drawerView, float slideOffset) {
            super.onDrawerSlide(drawerView, slideOffset);
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    if (!mUserLearnedDrawer && !mFromSavedInstanceState)
        mDrawerLayout.openDrawer(mNavigationDrawer);

    mDrawerLayout.post(new Runnable() {
        @Override
        public void run() {
            mDrawerToggle.syncState();
        }
    });
}

public static void saveToPreference(Context context, String preferenceName, String preferenceValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(preferenceName, preferenceValue);
    editor.apply();
//        editor.commit()
}

public static String readFromPreference(Context context, String preferenceName, String defaultValue) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE);
    return sharedPreferences.getString(preferenceName, defaultValue);
}
}

这是我的activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<include
    android:id="@+id/app_bar"
    layout="@layout/app_bar" />

<android.support.v4.widget.DrawerLayout
    android:name="@+id/main_DrawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="xymen.chetanbhagatnovels.MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/hello_world" />

    </RelativeLayout>

    <ListView
        android:id="@+id/navigation_drawer"
        android:layout_width="@dimen/navigation_drawer_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:divider="@null"/>

</android.support.v4.widget.DrawerLayout>
</LinearLayout>

mDrawerLayout.setDrawerListener(mDrawerToggle) 行给我错误; 我不知道为什么。我还有另一个项目,我从中复制了所有项目,但它也没有出错,但这个项目确实如此。帮助

根据您提供的有限信息,您的 mDrawerLayout 成员为空。

如果您在不同的布局文件夹中有多个版本的同一布局文件彼此不一致,就会发生这种情况。

我怀疑您的 res/layout 文件夹中有一个名为 main_activity.xml 的布局文件,它声明了一个 ID 为 main_DrawerLayout 的 DrawerLayout 视图,以及该布局文件的另一个版本(可能是在你的 res/layout-land 文件夹中)没有这个 DrawerLayout 视图,或者有它但用不同的视图 ID 声明。

因此,findViewById(R.id.main_DrawerLayout) 从您的备用 main_activity.xml 布局之一返回 null,结果您收到 NullPointerException。

我刚刚 运行 你的代码并弄明白了。

问题是您为 android.support.v4.widget.DrawerLayout 指定了 name 而不是 id

只需更改此:

android:name="@+id/main_DrawerLayout"

为此:

android:id="@+id/main_DrawerLayout"

通过该更改,NullPointerException 已修复,运行 对我来说没问题。