导航抽屉中的空例外

时间:2015-06-19 11:52:12

标签: java android xml

我在我的项目中应用导航抽屉。我要做的是在导航抽屉列表中添加三个项目,它们是FB_Fragment,TB_Fragment,G_fragment。当我点击这些项目中的任何一个时,它们各自的部分将会打开。所以我遇到的问题是当我运行我的项目时它会给我一个错误

" java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.abdul.navigation/com.example.abdul.navigation.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference " 

"Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)' on a null object reference "
  

MainActivity.java

package com.example.abdul.navigation;

import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import com.example.abdul.navigation.FB_Fragment;
import android.widget.ListView;
import com.example.abdul.navigation.G_fragment;
import com.example.abdul.navigation.TB_Fragment;

public class MainActivity extends ActionBarActivity {
String[] menutitles;  TypedArray menuIcons;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;

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

    setContentView(R.layout.activity_main);

    mTitle = mDrawerTitle = getTitle();
    menutitles = getResources().getStringArray(R.array.titles);
    menuIcons = getResources().obtainTypedArray(R.array.icons);
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerList = (ListView) findViewById(R.id.slider_list);

    rowItems = new ArrayList<RowItem>();

    for (int i = 0; i < menutitles.length; i++) {
        RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(      i, -1));
        rowItems.add(items);
    }

    menuIcons.recycle();
    adapter = new CustomAdapter(getApplicationContext(), rowItems);
    mDrawerList.setAdapter(adapter);
    mDrawerList.setOnItemClickListener(new SlideitemListener());

    // enabling action bar app icon and behaving it as toggle button
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_drawer, R.string.app_name,R.string.app_name)
    {
        public void onDrawerClosed(View view) {
            getSupportActionBar().setTitle(mTitle);
            // calling onPrepareOptionsMenu() to show action bar icons
            ActivityCompat.invalidateOptionsMenu(getParent());
        }
        public void onDrawerOpened(View drawerView) {
            getSupportActionBar().setTitle(mDrawerTitle);
            // calling onPrepareOptionsMenu() to hide action bar icons
            ActivityCompat.invalidateOptionsMenu(getParent());
        }
    };
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    if (savedInstanceState == null) {
        // on first time display view for first nav item
        updateDisplay(0);
    }
}




class SlideitemListener implements ListView.OnItemClickListener {

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

}  private void updateDisplay(int position) {
    Fragment fragment = null;
    switch (position) {
        case 0:      fragment = new FB_Fragment();
            break;
        case 1:       fragment = new G_fragment();
            break;
        case 2:         fragment = new TB_Fragment();
            break;
        default:
            break;
    }
    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
        // update selected item and title, then close the drawer
        setTitle(menutitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }
    else {
        // error in creating fragment
        Log.e("MainActivity", "Error in creating fragment");
    }
}
@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getSupportActionBar().setTitle(mTitle);
}

@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);
    }
}

/***   * 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);
}

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

}

CustomAdapter.java

package com.example.abdul.navigation;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomAdapter extends BaseAdapter {
Context context;  List<RowItem> rowItem;

CustomAdapter(Context context, List<RowItem> rowItem) {
    this.context = context;
    this.rowItem = rowItem;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        LayoutInflater mInflater = (LayoutInflater) context                     .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = mInflater.inflate(R.layout.list_tem, null);
    }
    ImageView imgIcon = (ImageView) convertView.findViewById(R.id.icon);
    TextView txtTitle = (TextView) convertView.findViewById(R.id.title);
    RowItem row_pos = rowItem.get(position);

    // setting the image resource and title
    imgIcon.setImageResource(row_pos.getIcon());
    txtTitle.setText(row_pos.getTitle());
    return convertView;
}

@Override
public int getCount() {
    return rowItem.size();
}

@Override
public Object getItem(int position) {
    return rowItem.get(position);
}

@Override
public long getItemId(int position) {
    return rowItem.indexOf(getItem(position));
}
}

Rowitem.java

package com.example.abdul.navigation;
public class RowItem {
private String title;
private int icon;
public RowItem(String title, int icon) {
    this.title = title;
    this.icon = icon;
}
public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public int getIcon() {
    return icon;
}
public void setIcon(int icon) {
    this.icon = icon;
}
}

FB_Fragment.java

package com.example.abdul.navigation;
import android.annotation.SuppressLint;
import android.app.Fragment;
import com.example.abdul.navigation.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@SuppressLint("NewApi")
public class FB_Fragment extends Fragment {

@Override public View onCreateView(LayoutInflater inflater, ViewGroup     container, Bundle savedInstanceState)
{
    View rootView = inflater .inflate(R.layout.fb_fragment, container, false);
    return rootView;
}
 }

TB_Fragment.java

package com.example.abdul.navigation;
import android.annotation.SuppressLint;
import android.app.Fragment;
import com.example.abdul.navigation.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@SuppressLint("NewApi")
public class TB_Fragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.tb_fragment, container, false);
        return rootView;
    }
}

G_fragment.java

package com.example.abdul.navigation;
import android.annotation.SuppressLint;
import android.app.Fragment;
import com.example.abdul.navigation.R;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@SuppressLint("NewApi")
public class G_fragment extends Fragment {

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
    View rootView = inflater .inflate(R.layout.g_fragment, container, false);
    return rootView;
}
}

activity_main.xml中

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- The main content view -->
<FrameLayout
    android:id="@+id/frame_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
<!-- The navigation drawer list -->
<ListView
    android:id="@+id/slider_list"
    android:layout_width="240dp"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:background="#ffffff"
    android:choiceMode="singleChoice"
    android:divider="@android:color/transparent"
    android:dividerHeight="0dp" />
</android.support.v4.widget.DrawerLayout>

fb_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="148dp"
    android:src="@drawable/fb" />
</RelativeLayout>

g_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="148dp"
    android:src="@drawable/gplus" />
</RelativeLayout>

list_tem.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="48dp"
android:padding="5dp" >
<ImageView
    android:id="@+id/icon"
    android:layout_width="50dp"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginLeft="12dp"
    android:layout_marginRight="12dp"
    android:contentDescription="@string/imgdesc" />
<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp"
    android:layout_toRightOf="@id/icon"
    android:gravity="center_vertical"
    android:textColor="#000000"
    android:textSize="20sp" />
</RelativeLayout>

tb_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
    android:id="@+id/imageView1"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="148dp"
    android:src="@drawable/tb" />
</RelativeLayout>

的strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

<string name="app_name">Navigation</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="imgdesc">imgdesc</string>
<string-array name="titles">
    <item>Facebook</item>
    <item>Google-Plus</item>
    <item>TutorialsBuzz</item>
</string-array>
<array name="icons">
    <item>@drawable/fb</item>
    <item>@drawable/gplus</item>
    <item>@drawable/tb</item>
</array>
</resources>

styles.xml

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
</style>

</resources>

1 个答案:

答案 0 :(得分:3)

在支持库中ActionBar使用

getSupportActionBar();

您正在使用getActionBar(),因此它正在提供null

所以用getActionBar()替换getSupportActionBar()

<强>更新

从styles.xml和中删除所有内容 在styles.xml中写下以下内容

<!--
    Base application theme, dependent on API level. This theme is replaced
    by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <!--
        Theme customizations available in newer API levels can go in
        res/values-vXX/styles.xml, while customizations related to
        backward-compatibility can go here.
    -->
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

希望这会对你有所帮助。