Android中的导航抽屉空指针异常

Posted

技术标签:

【中文标题】Android中的导航抽屉空指针异常【英文标题】:Navigation Drawer Null Pointer Exception in Android 【发布时间】:2015-01-10 06:14:33 【问题描述】:

android 中获取空指针异常 在下面发布我的代码以及 logcat 的屏幕截图(错误) MainActivity.java

package com.example.wabco;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity 

    // Within which the entire activity is enclosed
    private DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    private ListView mDrawerList;

    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    private ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) 

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = "JAVATECHIG.COM";
        getActionBar().setTitle(mTitle);

        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) 

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) 

                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu();

            

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) 
                getActionBar().setTitle("JAVATECHIG.COM");
                invalidateOptionsMenu();
            

        ;

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), 
                R.layout.drawer_list_item, getResources().getStringArray(R.array.menus));

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        getActionBar().setHomeButtonEnabled(true);

        // Enabling Up navigation
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() 

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) 

                // Getting an array of rivers
                String[] menuItems = getResources().getStringArray(R.array.menus);

                // Currently selected river
                mTitle = menuItems[position];

                // Creating a fragment object
                WebViewFragment rFragment = new WebViewFragment();

                // Passing selected item information to fragment
                Bundle data = new Bundle();
                data.putInt("position", position);
                data.putString("url", getUrl(position));
                rFragment.setArguments(data);


                // Getting reference to the FragmentManager
                FragmentManager fragmentManager = getFragmentManager();

                // Creating a fragment transaction
                FragmentTransaction ft = fragmentManager.beginTransaction();

                // Adding a fragment to the fragment transaction
                ft.replace(R.id.content_frame, rFragment);

                // Committing the transaction
                ft.commit();

                // Closing the drawer
                mDrawerLayout.closeDrawer(mDrawerList);

            
        );
    

    protected String getUrl(int position) 
        switch (position) 
        case 0:
            return "http://javatechig.com";
        case 1:
            return "http://javatechig.com/category/android/";
        case 2:
            return "http://javatechig.com/category/blackberry/";
        case 3:
            return "http://javatechig.com/category/j2me/";
        case 4:
            return "http://javatechig.com/category/sencha-touch/";
        case 5:
            return "http://javatechig.com/category/phonegap/";
        case 6:
            return "http://javatechig.com/category/java/";
        default:
            return "http://javatechig.com";
        
    

    @Override
    protected void onPostCreate(Bundle savedInstanceState) 
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    

    @Override
    public boolean onOptionsItemSelected(MenuItem item) 
        if (mDrawerToggle.onOptionsItemSelected(item)) 
            return true;
        
        return super.onOptionsItemSelected(item);
    

    /** Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) 
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    

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

添加布局和菜单代码 activity_main.xml

 <android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/drawer_layout"
        android:layout_
        android:layout_ >

        <!-- The main content view -->

        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_
            android:layout_ />
        <!-- The navigation drawer -->

        <ListView
            android:id="@+id/drawer_list"
            android:layout_
            android:layout_
            android:layout_gravity="start"
            android:background="#111"
            android:choiceMode="singleChoice"
            android:divider="@android:color/transparent"
            android:dividerHeight="0dp" />

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

drawer_list_item.xml

 <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_
        android:layout_
        android:background="?android:attr/activatedBackgroundIndicator"
        android:gravity="center_vertical"
        android:minHeight="?android:attr/listPreferredItemHeightSmall"
        android:paddingLeft="16dp"
        android:paddingRight="16dp"
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="#fff" />

fragment_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_
    android:layout_
    android:orientation="vertical" >

    <WebView
        android:id="@+id/webView"
        android:layout_
        android:layout_ />

</LinearLayout>

菜单 main.xml

<menu 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"
    tools:context="com.example.wabco.MainActivity" >

    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:title="@string/action_settings"
        app:showAsAction="ifRoom"/>

</menu>

【问题讨论】:

您尝试过扩展ActionBarActivity 而不是Activity 吗? 尝试改变 getActionBar().setTitle(mTitle);使用 getSupportActionBar().setTitle(mTitle); 如果我使用 getSupportActionBar 进行更改,我会收到一个错误 MainActivity 类型的方法 getSupportActionBar() 未定义。 你应该像@ρяσѕρєяK所说的那样扩展ActionBarActivity 对于以后的发布,您应该复制错误 logcat 输出并粘贴它们,而不是 logcat 输出的屏幕截图。 【参考方案1】:

对上面的代码进行下面提到的更改,它可以正常工作,

MainActivity 将“Activity”扩展为“ActionBarActivity”。

所有“getActionBar()”到“getSupportActionBar()

注意:导入android.support.v7.app.ActionBarActivity

【讨论】:

以上是关于Android中的导航抽屉空指针异常的主要内容,如果未能解决你的问题,请参考以下文章

导航抽屉中的谷歌地图 - 空指针异常,哪个是正确的片段?

带有 ListView 的导航抽屉。 ListView 上的空指针异常

Android 应用程序不断因空指针异常而崩溃

操作栏上不确定的进度条上的空指针异常

rootView上的Android片段空指针异常[关闭]

带导航抽屉的空指针