我第一次使用sharedPreferences,我似乎無法通過這個錯誤。我有一個應該允許用戶設置其區域的子菜單。這應該會打開正確的區域活動,並在應用程序再次打開時進行存儲和調用。 我一直在圍繞圈子多次,所以一些代碼會有點奇怪。我一直專注於從美國(默認)更改爲英國。SharedPreferences中的NullPointerException Android
在DDMS我得到這樣的:
05-13 11:22:39.344: ERROR/AndroidRuntime(960): java.lang.NullPointerException
05-13 11:22:39.344: ERROR/AndroidRuntime(960): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
05-13 11:22:39.344: ERROR/AndroidRuntime(960): at com.silifeform.android.Prefs.editRegion(Prefs.java:29)
05-13 11:22:39.344: ERROR/AndroidRuntime(960): at com.silifeform.android.dog.onOptionsItemSelected(dog.java:344)
我的代碼是這樣的:
public class Prefs extends Activity {
public static final String PREFS_NAME="LocalePrefs";
private String region;
public boolean isUk;
public boolean isUs;
public boolean isEu;
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
//restore prefs
SharedPreferences settings= getSharedPreferences(PREFS_NAME,0);
String myRegion = settings.getString(region,"us");
this.region=myRegion;
changeLocale(getRegion());
}
public void editRegion(String sregion) {
// The error occurs here:
SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
SharedPreferences.Editor ed = settings.edit();
ed.clear();
ed.putString(region,sregion);
ed.commit();
}
public String getRegion(){
SharedPreferences settings= getSharedPreferences(PREFS_NAME,0);
String myRegion = settings.getString(region,"us");
String gRegion=myRegion;
return gRegion;
}
public void changeLocale(String locale){
try{
String l= locale;
if(l==("us")){
this.isUs=true;
Toast.makeText(this, "Us region P selected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Prefs.this, dog.class);
startActivity(intent);
}
if(l.equals("uk")){
this.isUk=true;
//Toast.makeText(this, "UK region selected", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Prefs.this, cat.class);
startActivity(intent);
}
}catch (NullPointerException e){
//what to do here?
finish();
}
}
@Override
protected void onStop() {
super.onStop();
SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor ed = settings.edit();
ed.putString(region,region);
ed.commit();
}
在狗類我的子菜單中的代碼如下所示:
public boolean onOptionsItemSelected(MenuItem item){
Prefs pob = new Prefs();
switch (item.getItemId()){
//-------Options menu----------
case R.id.about:
//Toast.makeText(this, "About menu", Toast.LENGTH_SHORT).show();
//showAbout();
return true;
case R.id.locale:
//Toast.makeText(this, "Locale menu", Toast.LENGTH_SHORT).show();
return true;
//-----Sub menu----------
case R.id.uk_item:
Toast.makeText(this, "UK selected", Toast.LENGTH_SHORT).show();
pob.editRegion("uk");
pob.changeLocale("uk");
finish();
return true;
case R.id.us_item:
Toast.makeText(this, "US already selected", Toast.LENGTH_SHORT).show();
pob.changeLocale("us");
//finish();
return true;
default :
return super.onOptionsItemSelected(item);
}
謝謝
代碼中的哪行會產生錯誤? – Egor 2011-05-13 11:46:35