从字符串数组中获取片段标题

Get fragment title from string array

所以我正在使用基于 ActionBarSherlock 的示例应用程序。我想从字符串数组中设置片段的标题,但是当我尝试在模拟器上 运行 它时,它给了我 NullPointerException 错误。

String[] title;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String[] title = context.getResources().getStringArray(R.array.title);
private void selectItem(int position) {
    setTitle(title[position]);
}

这只是我认为涉及的代码的一部分。 但这是我的全部代码。

package com.androidbegin.menuviewpagertutorial;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;

public class MainActivity extends SherlockFragmentActivity {

// Declare Variables
DrawerLayout mDrawerLayout;
ListView mDrawerList;
ActionBarDrawerToggle mDrawerToggle;
MenuListAdapter mMenuAdapter;
String[] title;
String[] subtitle;
int[] icon;
Fragment fragment1 = new Fragment1();
Fragment fragment2 = new Fragment2();
private CharSequence mDrawerTitle;
private CharSequence mTitle;
Context context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from drawer_main.xml
    setContentView(R.layout.drawer_main);

    // Get the Title
    mTitle = mDrawerTitle = getTitle();

    // Generate title
    String[] title = context.getResources().getStringArray(R.array.title);

    // Generate subtitle
    subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2" };

    // Generate icon
    icon = new int[] { R.drawable.action_about, R.drawable.action_settings };

    // Locate DrawerLayout in drawer_main.xml
    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

    // Locate ListView in drawer_main.xml
    mDrawerList = (ListView) findViewById(R.id.listview_drawer);

    // Set a custom shadow that overlays the main content when the drawer
    // opens
    mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
            GravityCompat.START);

    // Pass string arrays to MenuListAdapter
    mMenuAdapter = new MenuListAdapter(MainActivity.this, title, subtitle);

    // Set the MenuListAdapter to the ListView
    mDrawerList.setAdapter(mMenuAdapter);

    // Capture listview menu item click
    mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

    // Enable ActionBar app icon to behave as action to toggle nav drawer
    getSupportActionBar().setHomeButtonEnabled(true);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    // ActionBarDrawerToggle ties together the the proper interactions
    // between the sliding drawer and the action bar app icon
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
            R.drawable.ic_drawer, R.string.drawer_open,
            R.string.drawer_close) {

        public void onDrawerClosed(View view) {
            // TODO Auto-generated method stub
            super.onDrawerClosed(view);
        }

        public void onDrawerOpened(View drawerView) {
            // TODO Auto-generated method stub
            // Set the title on the action when drawer open
            getSupportActionBar().setTitle(mDrawerTitle);
            super.onDrawerOpened(drawerView);
        }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if (item.getItemId() == android.R.id.home) {

        if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            mDrawerLayout.openDrawer(mDrawerList);
        }
    }

    return super.onOptionsItemSelected(item);
}

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

private void selectItem(int position) {

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    // Locate Position
    switch (position) {
    case 0:
        ft.replace(R.id.content_frame, fragment1);
        break;
    case 1:
        ft.replace(R.id.content_frame, fragment2);
        break;
    }
    ft.commit();
    mDrawerList.setItemChecked(position, true);
    // Get the title followed by the position
    setTitle(title[position]);
    // Close drawer
    mDrawerLayout.closeDrawer(mDrawerList);
}

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

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getSupportActionBar().setTitle(mTitle);
}

@Override
public void onBackPressed() {

    FragmentManager manager = getSupportFragmentManager();
    if (manager.getBackStackEntryCount() > 0) {
        // If there are back-stack entries, leave the FragmentActivity
        // implementation take care of them.
        manager.popBackStack();

    } else {
        // Otherwise, ask user if he wants to leave :)
        super.onBackPressed();
    }
}
}

Logcat:

02-19 13:42:31.357: E/AndroidRuntime(1877): FATAL EXCEPTION: main
02-19 13:42:31.357: E/AndroidRuntime(1877): Process:                com.androidbegin.menuviewpagertutorial, PID: 1877
02-19 13:42:31.357: E/AndroidRuntime(1877): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.androidbegin.menuviewpagertutorial/com.androidbegin.menuviewpagertutorial.MainActivity}: java.lang.NullPointerException
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread.access0(ActivityThread.java:135)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.os.Handler.dispatchMessage(Handler.java:102)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.os.Looper.loop(Looper.java:136)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread.main(ActivityThread.java:5017)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at java.lang.reflect.Method.invokeNative(Native Method)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at java.lang.reflect.Method.invoke(Method.java:515)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at dalvik.system.NativeStart.main(Native Method)
02-19 13:42:31.357: E/AndroidRuntime(1877): Caused by: java.lang.NullPointerException
02-19 13:42:31.357: E/AndroidRuntime(1877):     at com.androidbegin.menuviewpagertutorial.MainActivity.selectItem(MainActivity.java:143)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at com.androidbegin.menuviewpagertutorial.MainActivity.onCreate(MainActivity.java:99)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.Activity.performCreate(Activity.java:5231)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-19 13:42:31.357: E/AndroidRuntime(1877):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-19 13:42:31.357: E/AndroidRuntime(1877):     ... 11 more

我不太明白mDrawerTitle和mTitle的用法,所以请帮助我理解并解决这个问题。

提前致谢。

上下文似乎没有被初始化,改变你的这一行

String[] title = context.getResources().getStringArray(R.array.title); 

String[] title = getBaseContext().getResources().getStringArray(R.array.title);