I am creating an app with several activities. SharedPreferences are read in multiple activities.
I have found that when I update a single variable in one of the SharedPreferences files, all of the variables in that file take on the value assigned.
Is there a general reason why this might occur? If not, I can post code.
THE FOLLOWING CODE IS USED TO WRITE AND READ THE VALUES (anything in all caps is a unique integer constant)
public void LevelUp(int gameType) {
step++;
SharedPreferences settings = getSharedPreferences("Steps", 0);
SharedPreferences.Editor editor = settings.edit();
switch (gameType) {
case NUMBERS_SPEED: editor.putInt("NUMBERS_SPEED", step);
case NUMBERS_BINARY: editor.putInt("NUMBERS_BINARY", step);
case NUMBERS_SPOKEN: editor.putInt("NUMBERS_SPOKEN", step);
case LISTS_WORDS: editor.putInt("LISTS_WORDS", step);
case LISTS_EVENTS: editor.putInt("LISTS_EVENTS", step);
case SHAPES_FACES: editor.putInt("SHAPES_FACES", step);
case SHAPES_ABSTRACT: editor.putInt("SHAPES_ABSTRACT", step);
case CARDS_SPEED: editor.putInt("CARDS_SPEED", step);
}
editor.commit();
}
public int getStep(int gameType) {
SharedPreferences settings = getSharedPreferences("Steps", 0);
switch (gameType) {
case NUMBERS_SPEED: return settings.getInt("NUMBERS_SPEED", 1);
case NUMBERS_BINARY: return settings.getInt("NUMBERS_BINARY", 1);
case NUMBERS_SPOKEN: return settings.getInt("NUMBERS_SPOKEN", 1);
case LISTS_WORDS: return settings.getInt("LISTS_WORDS", 1);
case LISTS_EVENTS: return settings.getInt("LISTS_EVENTS", 1);
case SHAPES_FACES: return settings.getInt("SHAPES_FACES", 1);
case SHAPES_ABSTRACT: return settings.getInt("SHAPES_ABSTRACT", 1);
case CARDS_SPEED: return settings.getInt("CARDS_SPEED", 1);
default: return -1;
}
}
THE FOLLOWING CODE RESIDES IN A DIFFERENT ACTIVITY:
SharedPreferences settings = getSharedPreferences("Steps", 0);
step = settings.getInt("NUMBERS_SPOKEN", 1);
You need breaks between your case statements
Otherwise it will go through every case statement which is why they are all getting assigned that value