Android:集成导航抽屉,提供空对象引用错误

时间:2015-08-31 08:11:41

标签: android android-fragments navigation-drawer

我正在开发一个Android应用程序,我正在尝试集成Navigation Drawer。现在,该项目分为两部分,一部分是用户,一部分是餐馆。两者都是不同的项目,所以两者都有不同的APK和所有。 现在,用户的抽屉工作得很好。我在餐厅使用了相同的代码,它给我一个错误。我不知道为什么。基本上,我在该类中创建了一个Drawer Layout活动和扩展活动。无论我想要一个抽屉,我都在扩展DrawerLayoutActivity类,而不是普通的活动,并在XML中添加列表和android抽屉布局。它在User中运行。以下是相关代码:

错误日志:

  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference
            at internetlegion.com.restaurantlunchify.RestaurantDrawer.RestaurantDrawerActivity.set(RestaurantDrawerActivity.java:90)
            at internetlegion.com.restaurantlunchify.Activity.AddRestaurantImages.onCreate(AddRestaurantImages.java:42)
            at android.app.Activity.performCreate(Activity.java:5958)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1129)

RestaurantDrawerActivity

public class RestaurantDrawerActivity extends Activity{

    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    // nav drawer title
    private CharSequence mDrawerTitle;

    // used to store app title
    private CharSequence mTitle;

    // slide menu items/*
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

    private ArrayList<DrawerModel> navDrawerItems;
    private RestaurantDrawerListAdapter adapter;

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


    }
    public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
        mTitle = mDrawerTitle = getTitle();
        navMenuTitles = getResources().getStringArray(R.array.restaurant_nav_drawer_items);
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.restaurant_drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.restaurant_list_slidermenu);
        navDrawerItems = new ArrayList<DrawerModel>();

            /*for (int i = 0; i < navMenuTitles.length; i++) {
                navDrawerItems.add(new DrawerModel(navMenuTitles[i],
                        navMenuIcons.getResourceId(i, -1)));
            }*/

        navDrawerItems.add(new DrawerModel(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        // Find People
        navDrawerItems.add(new DrawerModel(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
        // Photos
        navDrawerItems.add(new DrawerModel(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        // Communities, Will add a counter here
        navDrawerItems.add(new DrawerModel(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        // Pages
        navDrawerItems.add(new DrawerModel(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        // What's hot, We  will add a counter here
        navDrawerItems.add(new DrawerModel(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));

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

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new RestaurantDrawerListAdapter(getApplicationContext(),
                navDrawerItems);
        mDrawerList.setAdapter(adapter);

// The line below fails
       getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, //nav menu toggle icon
                R.string.app_name, // nav drawer open - description for accessibility
                R.string.app_name // nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                // calling onPrepareOptionsMenu() to show action bar icons
                invalidateOptionsMenu();
            }

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


    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // toggle nav drawer on selecting action bar app icon/title
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action bar actions click
        switch (item.getItemId()) {
            case R.id.action_settings:
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
   @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * 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.
        mDrawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

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


    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item

            displayView(position);
        }
    }
}

这就是我使用它的方式:

public class AddRestaurantImages extends RestaurantDrawerActivity {
    private static final int CAMERA_PIC_REQUEST = 22;
    Button BtnSelectImage;
    private ImageView ImgPhoto;
    Bitmap photo;
    int menucardid;

    RestaurantServiceImpl restaurantService = new RestaurantServiceImpl();

    private String[] navMenuTitles;
    private TypedArray navMenuIcons;

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

        navMenuTitles = getResources().getStringArray(R.array.restaurant_nav_drawer_items);
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        set(navMenuTitles, navMenuIcons);

那么,到底出了什么问题。任何帮助都会很好。非常感谢。 : - )

必要时

更新 XML文件:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/restaurant_drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="top|center"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <Button
            android:id="@+id/BtnSelectImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Insert Image" />

        <Button
            android:id="@+id/uploadImageButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:text="Upload restImage" />

        <ImageView
            android:id="@+id/ImgPhoto"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/ic_launcher" />

        <Button
            android:id="@+id/up"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Upload Image" />
    </LinearLayout>

    <ListView
        android:id="@+id/restaurant_list_slidermenu"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:dividerHeight="1dp" />

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

1 个答案:

答案 0 :(得分:1)

您尝试在操作栏上调用 setDisplayHomeAsUpEnabled(boolean)函数,而无需设置操作栏。

我建议只为工具栏创建一个新的布局。这是使用支持库的示例。

<强> toolbar.xml

<android.support.v7.widget.Toolbar   xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:elevation="4dp"
    android:background="?attr/colorPrimary"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

修改属性以满足您的需求。

在下一步中,您将此布局包含在 restaurant_drawerlayout.xml 文件中,如下所示:

 <include layout="@layout/toolbar" />

这样,您可以在所有布局中使用相同的工具栏布局文件。

然后在 set(String [] navMenuTitles,TypedArray navMenuIcons)中执行以下操作:

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

执行此操作后,您可以使用

获取操作栏
getSupportActionBar()

应该很高兴。