0

Initializing highScore array :

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

Checking For the 4 Highest Values :

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

This is my code for saving data in shared preferences

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

2 Answers2

1

I will suggest to use like that.

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();
Nitin Karande
  • 1,280
  • 14
  • 33
0

Instead of commiting after completing the if loop , commit in each iteration of your loop like this:

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

it will work.

Anjali
  • 1
  • 1
  • 13
  • 20