2016-11-23 174 views
0

初始化高分陣列:共享偏好不保存數據

score = 0; 
sharedPreferences = context.getSharedPreferences("Scores", Context.MODE_PRIVATE); 
    //initialize the array of high scores 
    highScore[0] = sharedPreferences.getInt("score1",0); 
    highScore[1] = sharedPreferences.getInt("score2",0); 
    highScore[2] = sharedPreferences.getInt("score3",0); 
    highScore[3] = sharedPreferences.getInt("score4",0); 
    highScore[4] = sharedPreferences.getInt("score5",0); 

檢查對於4個最高值:

highScore[5] = score; 
Arrays.sort(highScore); 

這是我在共享偏好保存數據代碼

SharedPreferences.Editor e = sharedPreferences.edit(); 
       for(int j=4;j>=0;j--){ 
        e.putInt("score"+(j+1),highScore[j]); 
        e.apply(); 
       } 
+0

請在這裏檢查:http://stackoverflow.com/questions/23024831/android-shared-preferences-example –

+0

這是完整的代碼保存價值的偏好? –

+0

你是否用關鍵「分數」初始化了sharedPreferences? – Madhav

回答

1

我會建議像那樣使用。

SharedPreferences pref; 
pref= context.getSharedPreferences("Scores", Context.MODE_PRIVATE); 
SharedPreferences.Editor e = pref.edit(); 
      for(int j=4;j>=0;j--){ 
       e.putInt("score"+(j+1),highScore[i]); 
      } 
      e.apply(); 
+0

我的SharedPreferences對象是公開的 'public SharedPreferences sharedPreferences;' – JDFuzyll

+0

@JDFuzyll你試過嗎?我建議每次使用時都要加載共享首選項對象。不是全局存儲。 – Doomsknight

+0

非常感謝 它確實工作 – JDFuzyll

0

相反commiting的完成,如果循環結束後,犯這樣你每次循環:

SharedPreferences.Editor e = sharedPreferences.edit(); 
       for(int j=4;j>=0;j--){ 
        e.putInt("score"+(j+1),highScore[i]); 
           e.apply(); 
    } 

它會奏效。

+0

即使這不起作用 – JDFuzyll