由getActionBar()引起的NullPointerException

时间:2015-01-31 19:20:22

标签: java android nullpointerexception android-actionbar

现在尝试设置应用程序的导航抽屉,每次我尝试在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):致命异常:主要   01-31 14:11:11.298:E / AndroidRuntime(20904):流程:   appathon.bu.com.appathon,PID:20904 01-31 14:11:11.298:   E / AndroidRuntime(20904):java.lang.RuntimeException:无法启动   活动   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.access $ 800(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):引起: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

2 个答案:

答案 0 :(得分:14)

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

其次,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(或从中继承的内容)作为活动的主题

答案 1 :(得分:0)

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