Im trying to store the top 5 high scores inside a sharedpreference
instead of an sqlite
database. So I looked around and found two methods (saveArray and loadArray) from a stack post here ( Is it possible to add an array or object to SharedPreferences on Android )
Anyway when I try and add in a value to the array I get an arrayoutofbounds
error. java.lang.ArrayIndexOutOfBoundsException: length=0;index=0
Because the user will not start with values in the array I'm trying to determine if the array has a value at position i, If not I am trying to insert the score that was passed into the array at that position. But it won't work and I'm not sure why?
So essentially if highscores[i] != null
then I'll go and check to see if highscores[i] < intScore
, if highscores is < intScore
then I will replace it with the passed score in the constructor.
String[] highscores = new String[5];
public void editHighscores(String score){
int intScore = Integer.parseInt(score);
highscores = loadArray("highscores",this.getApplicationContext());
// Checks to see if index is empty
for(int i=0;i<5; i++){
if(highscores[i] == null){
highscores[i] = score;
} else{
if(Integer.parseInt(highscores[i]) < intScore){
highscores[i] = score;
}
}
Log.d("index - " + i, "Value = " + highscores[i]);
}
// Save the array
saveArray(highscores, "highscores", this.getApplicationContext());
}
public boolean saveArray(String[] array, String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("highscoresPref", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
public String[] loadArray(String arrayName, Context mContext) {
SharedPreferences prefs = mContext.getSharedPreferences("highscoresPref", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}