尝试调用虚方法' void android.support.v4.app.ActionBarDrawerToggle.syncState()'在null对象引用上

时间:2015-03-04 08:54:24

标签: android navigation-drawer

我尝试了导航抽屉。但是,发生了异常。

为什么会出现错误信息? 你介意你能解决这个问题吗?


MainActivity.java

public class MainActivity extends Activity implements OnPageChangeListener, OnClickListener {
private ListView listView;
private ViewPager mPager;

private String[] navItems = {"Brown", "Cadet Blue", "Dark Olive Green", "Dark Orange", "Golden Rod"};
private ListView lvLeftSlideMenu;
private FrameLayout flMainContent;
private DrawerLayout dlDrawer;
private ActionBarDrawerToggle dtToggle;


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

    listView = (ListView) findViewById(R.id.list);
    mAdapter = new MainListAdapter(this);

    listView.setAdapter(mAdapter);
    listView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        ...
        }
    });

    mPager = (ViewPager)findViewById(R.id.pager);
    mPager.setAdapter(new MyPagerAdapter(getApplicationContext()));

    flMainContent = (FrameLayout) findViewById(R.id.fl_main_content);
    lvLeftSlideMenu = (ListView) findViewById(R.id.lv_left_slide_menu);
    lvLeftSlideMenu.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, navItems));
    lvLeftSlideMenu.setOnItemClickListener(new DrawerItemClickListener());

    dlDrawer = (DrawerLayout)findViewById(R.id.dl_activity_main_drawer);
    dtToggle = new ActionBarDrawerToggle(this, dlDrawer, R.drawable.ic_drawer, R.string.open_drawer, R.string.close_drawer) {
        @Override
        public void onDrawerClosed(View drawerView) {
            super.onDrawerClosed(drawerView);
        }
        @Override
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
        }
    };
    dlDrawer.setDrawerListener(dtToggle);
    getActionBar().setDisplayHomeAsUpEnabled(true);

}

protected void onPostCreate(Bundle savedInstanceState){
    super.onPostCreate(savedInstanceState);
    dtToggle.syncState();       // exception occurred...
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    if(dtToggle.onOptionsItemSelected(item)){
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    // TODO Auto-generated method stub
    super.onConfigurationChanged(newConfig);
    dtToggle.onConfigurationChanged(newConfig);
}

private class DrawerItemClickListener implements ListView.OnItemClickListener{

    @Override
    public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
        switch(position){
        case 0:
            flMainContent.setBackgroundColor(Color.parseColor("#A52A2A"));
            break;
        case 1:
            flMainContent.setBackgroundColor(Color.parseColor("#5F9EA0"));
            break;
        case 2:
            flMainContent.setBackgroundColor(Color.parseColor("#556B2F"));
            break;
        case 3:
            flMainContent.setBackgroundColor(Color.parseColor("#FF8C00"));
            break;
        case 4:
            flMainContent.setBackgroundColor(Color.parseColor("#DAA520"));
            break;
        }

        dlDrawer.closeDrawer(lvLeftSlideMenu);
    }

}


 private class MyPagerAdapter extends PagerAdapter {
    private LayoutInflater mInflater;

    public MyPagerAdapter(Context context) {
        super();
        mInflater = LayoutInflater.from(context);

    }

    @Override 
    public int getCount() { 
        return 2;
    }

    @Override 
    public Object instantiateItem(View pager, int position) {
        View v = null;

        if(position==0) {
            v = mInflater.inflate(R.layout.main_menu_01, null);
                                ...

        } else if(position==1) {
            v = mInflater.inflate(R.layout.main_menu_02, null);
                                ...
        }
        ((ViewPager)pager).addView(v, 0);
        return v; 
    }

    @Override
    public void destroyItem(View pager, int position, Object view) {
        ((ViewPager)pager).removeView((View)view);
    }

    @Override 
    public boolean isViewFromObject(View view, Object obj) { 
        return view == obj; 
    }

    @Override public void finishUpdate(View arg0) { }
    @Override public void restoreState(Parcelable arg0, ClassLoader arg1) {}
    @Override public Parcelable saveState() { return null; }
    @Override public void startUpdate(View arg0) {}

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

 }

@Override
public void onPageScrollStateChanged(int arg0) {}

@Override
public void onPageScrolled(int arg0, float arg1, int arg2) {}

@Override
public void onPageSelected(int position) {}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        finish();
    }
    return false;
} 

}

activity_main.xml中

<!-- Main Layout -->
<FrameLayout
    android:id="@+id/fl_main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/all_blank" >

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <RelativeLayout
            android:id="@+id/titlebar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/main_tit" >

            <LinearLayout
                android:id="@+id/linearLayout1"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true" >

                <TextView
                    android:id="@+id/userInfo"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_centerVertical="true"
                    android:layout_marginRight="10px"
                    android:gravity="left"
                    android:textColor="@color/grayblack"
                    android:textSize="12dp" />
            </LinearLayout>

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@id/userInfo" >
            </LinearLayout>

            <TextView
                android:id="@+id/userJisa"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_below="@+id/linearLayout1"
                android:layout_marginRight="10px"
                android:gravity="left"
                android:textColor="@color/grayblack"
                android:textSize="12dp" />
        </RelativeLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/sub_tit_01"
            android:orientation="vertical" >

            <ImageView
                android:id="@+id/btnRefresh"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="right"
                android:layout_marginTop="1.0dip"
                android:paddingRight="6.0dip"
                android:src="@drawable/icon_refresh" />
        </LinearLayout>

        <LinearLayout
            android:id="@+id/topBg"
            android:layout_width="match_parent"
            android:layout_height="164dp"
            android:background="@drawable/top_bg"
            android:gravity="center"
            android:orientation="vertical" >

            <ListView
                android:id="@+id/list"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:drawSelectorOnTop="false" />

        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/sub_tit_02"
            android:orientation="vertical" >
        </LinearLayout>

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/bottom_bg"
            android:orientation="vertical" >

            <android.support.v4.view.ViewPager
                android:id="@+id/pager"
                android:layout_width="match_parent"
                android:layout_height="200dip" />

            <RelativeLayout
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@drawable/location_area"
                android:gravity="center"
                android:orientation="horizontal" >

                <LinearLayout
                    android:id="@+id/page_mark"
                    android:layout_width="fill_parent"
                    android:layout_height="30dp"
                    android:layout_centerInParent="true"
                    android:gravity="center"
                    android:orientation="horizontal" />

                <TextView
                    android:id="@+id/versionInfo"
                    android:layout_width="wrap_content"
                    android:layout_height="30dp"
                    android:layout_alignParentRight="true"
                    android:gravity="bottom"
                    android:textColor="@color/grayblack"
                    android:textSize="12sp" />
            </RelativeLayout>
        </LinearLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/notice_bg"
            android:gravity="center"
            android:orientation="horizontal" >

            <ViewFlipper
                android:id="@+id/ViewFlipper01"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center" >
            </ViewFlipper>
        </LinearLayout>
    </LinearLayout>

</FrameLayout>
<!-- Main Layout -->

<!-- Left Slide Menu -->
<ListView 
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:id="@+id/lv_left_slide_menu"
    android:layout_gravity="start"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp"
    android:background="#EDEDED"/>
<!-- Left Slide Menu -->

错误消息

    FATAL EXCEPTION: main
Process: com.ex.himan.safetyPatrol, PID: 19664
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ex.himan.safetyPatrol/com.ex.himan.safetyPatrol.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.ActionBarDrawerToggle.syncState()' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2712)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2779)
    at android.app.ActivityThread.access$900(ActivityThread.java:179)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1462)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:5974)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1388)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1183)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.app.ActionBarDrawerToggle.syncState()' on a null object reference
    at com.ex.himan.safetyPatrol.MainActivity.onPostCreate(MainActivity.java:260)
    at android.app.Instrumentation.callActivityOnPostCreate(Instrumentation.java:1200)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2694)
    ... 10 more

1 个答案:

答案 0 :(得分:0)

getActionBar()方法返回null,因此您将获得NullPointerException.Use ActionBarActivity而不是Activity,如下所示

MainActivity extends ActionBarActivity

而不是getActionBar()而是使用getSupportActionBar()。希望它会有所帮助。