由 getActionBar() 引起的 NullPointerException

NullPointerException Caused by getActionBar()

现在正在尝试设置应用程序的导航抽屉,每次我尝试 运行 我的 Android 设备上的应用程序时,我都会收到 NullPointerException。错误是由 getActionBar.setDisplayHomeUpAsEnabled(true)getActionBar.setHomeButtonEnabled(true)

引起的

即使我删除这两行代码,我仍然会出错。

如何快速解决这个问题?

代码:

import android.app.Activity;
import android.app.Fragment;
import android.content.res.Configuration;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;


public class MainActivity extends Activity {
    private String[] navDrawerTitles;
    private DrawerLayout navDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    private CharSequence mTitle;
    Fragment fragment = new Fragment();
    private Fragment blankFrag = new Fragment();
    private final int POSITION = 0;


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

        navDrawerTitles = getResources().getStringArray(R.array.nav_array);
        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // Set the adapter for the list view
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, navDrawerTitles));

        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        navDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
                navDrawerLayout, /* DrawerLayout object */
                //R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
                R.string.drawer_open, /* "open drawer" description */
                R.string.drawer_close /* "close drawer" description */
        ) {

            /** Called when a drawer has settled in a completely closed state. */
            public void onDrawerClosed(View view) {
                // super.onDrawerClosed(view);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }

            /** Called when a drawer has settled in a completely open state. */
            public void onDrawerOpened(View drawerView) {
                // super.onDrawerOpened(drawerView);
                getActionBar().setTitle(R.string.app_name);
                invalidateOptionsMenu();
            }
        };

        // Set the drawer toggle as the DrawerListener
        navDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the nav drawer is open, hide action items related to the content
        // view
        boolean drawerOpen = navDrawerLayout.isDrawerOpen(mDrawerList);
        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        // Pass the event to ActionBarDrawerToggle, if it returns
        // true, then it has handled the app icon touch event
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private class DrawerItemClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            selectItem(position);
        }
    }


    /** Swaps fragments in the main content view */
    /**
     * Starts an Activity when item is clicked
     */
    private void selectItem(int position) {

//        }

        Bundle args = new Bundle();
        args.putInt(StartingFragment.TEA_TYPE_POS, position);
        fragment.setArguments(args);

        // Highlight the selected item, update the title, and close the drawer
        mDrawerList.setItemChecked(position, true);
//      setTitle(navDrawerTitles[position]);
        navDrawerLayout.closeDrawer(mDrawerList);

    }

    @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);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

}

01-31 14:11:11.298: E/AndroidRuntime(20904): FATAL EXCEPTION: main 01-31 14:11:11.298: E/AndroidRuntime(20904): Process: appathon.bu.com.appathon, PID: 20904 01-31 14:11:11.298: E/AndroidRuntime(20904): java.lang.RuntimeException: Unable to start activity ComponentInfo{appathon.bu.com.appathon/appathon.bu.com.appathon.MainActivity}: java.lang.NullPointerException 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2212) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2271) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread.access0(ActivityThread.java:144) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1205) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.os.Handler.dispatchMessage(Handler.java:102) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.os.Looper.loop(Looper.java:136) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread.main(ActivityThread.java:5146) 01-31 14:11:11.298: E/AndroidRuntime(20904): at java.lang.reflect.Method.invokeNative(Native Method) 01-31 14:11:11.298: E/AndroidRuntime(20904): at java.lang.reflect.Method.invoke(Method.java:515) 01-31 14:11:11.298: E/AndroidRuntime(20904): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796) 01-31 14:11:11.298: E/AndroidRuntime(20904): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612) 01-31 14:11:11.298: E/AndroidRuntime(20904): at dalvik.system.NativeStart.main(Native Method) 01-31 14:11:11.298: E/AndroidRuntime(20904): Caused by: java.lang.NullPointerException 01-31 14:11:11.298: E/AndroidRuntime(20904): at appathon.bu.com.appathon.MainActivity.onCreate(MainActivity.java:45) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.Activity.performCreate(Activity.java:5231) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 01-31 14:11:11.298: E/AndroidRuntime(20904): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169) 01-31 14:11:11.298: E/AndroidRuntime(20904): ... 11 more

首先,如果 Activity 中的 getActionBar() 返回 null,那么您的 activity 中没有原生操作栏。

其次,android.support.v7.app.ActionBarDrawerToggle 不适用于本机操作栏。它与 appcompat-v7 操作栏反向移植一起使用。如果您打算使用 android.support.v7.app.ActionBarDrawerToggle,那么您必须将您的应用移至使用 appcompat-v7:

  1. 添加appcompat-v7作为依赖项

  2. 继承自ActionBarActivity而不是Activity

  3. 调用 getSupportActionBar() 而不是 getActionBar()

  4. 使用 Theme.AppCompat(或继承自它的东西)作为您 activity 的主题

我和你有同样的错误。我的解决方案是使用 ThemeAppCompat 设置主题,使您的 activity 扩展 AppCompatActivity 并使用 getSupportActionBar 方法而不是使用 getActionBar 方法。总之,要确保主题的actionBar和获取actionBar的方法有相同的支持库。