2016-11-23 171 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