空指针异常DrawerLayout

时间:2015-07-17 22:53:43

标签: java android nullpointerexception runtime-error 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)上给我错误; 我不知道为什么。我还有另一个项目,我已经复制了所有项目,但它也没有收到错误,但这个项目确实如此。帮助

2 个答案:

答案 0 :(得分:1)

根据您提供的有限信息,您的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。

答案 1 :(得分:1)

我只是运行你的代码然后想出来了。

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

只需改变一下:

android:name="@+id/main_DrawerLayout"

对此:

android:id="@+id/main_DrawerLayout"

通过这个更改,修复了NullPointerException并且它对我运行正常。