共享首选项空指针异常

时间:2011-10-05 06:31:12

标签: android

//Activity-- mTweetApp.SetCaseInfo(type,teet); //storing in another class

public void SetCaseInfo(String PatientType,ArrayList arr){
   // All objects are from 
   SharedPreferences settings =setSharedPreferences(DEALSPOTR_PREFS,0);
   SharedPreferences.Editor editor = settings.edit();
   editor.putInt("arrayLength",arr.size());
   for(int i=0; i<=arr.size(); i++){
      editor.putInt("Teethsselected"+String.valueOf(i), (Integer) arr.get(i));
   }
   editor.putString("view", PatientType);
   for(int i=0; i<=arr.size(); i++){
       System.out.println("Teethsselected-----"+(Integer) arr.get(i)+"type--->"+PatientType);
   }
}

public void getCaseInfo() {
   SharedPreferences settings =getSharedPreferences(DEALSPOTR_PREFS, 0);
   int arraySize = settings.getInt("arrayLength", 0); 
   int teeth[] =new int[arraySize];
   for(int i=0; i<arraySize; i++){
      teeth[i] = ettings.getInt("Teethsselected"+String.valueOf(i),0);
   } 
   String type =settings.getString("view"," ");
}

如何解决这个问题?

4 个答案:

答案 0 :(得分:3)

您不提交更改。将editor.commit();放入您的set方法。

答案 1 :(得分:0)

SharedPreferences.Editor修改应为commit ed。

   //Your code
   editor.putString("view", PatientType);
   for(int i=0; i<=arr.size(); i++){
       System.out.println("Teethsselected-----"+(Integer) arr.get(i)+"type--->"+PatientType);
   }
   //ADD THIS
   editor.commit();

答案 2 :(得分:0)

首先,当您编写pref值时,不会调用commit()
其次,pref文件没有写入/data/data/com.package.App/shared_prefs/pref_file.xml,因此读取SharedPreferences对象时为NULL。

答案 3 :(得分:0)

SharedPreferences settings =setSharedPreferences(DEALSPOTR_PREFS,0);

而不是上面的行,请尝试使用

SharedPreferences settings =getSharedPreferences(DEALSPOTR_PREFS,0);

并且在添加值后不要忘记editor.commit()行。