我正在创建一个包含多项活动的应用。 SharedPreferences在多个活动中被读取。
我发现当我更新其中一个SharedPreferences文件中的单个变量时,该文件中的所有变量都会占用指定的值。
是否有可能发生这种情况的一般原因?如果没有,我可以发布代码。
以下代码用于写入和读取值(所有大写的内容都是唯一的整数常量)
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;
}
}
以下代码保留了不同的活动:
SharedPreferences settings = getSharedPreferences("Steps", 0);
step = settings.getInt("NUMBERS_SPOKEN", 1);
答案 0 :(得分:2)
您需要在案例陈述之间中断
switch (gameType) {
case NUMBERS_SPEED: editor.putInt("NUMBERS_SPEED", step);
break;
case NUMBERS_BINARY: editor.putInt("NUMBERS_BINARY", step);
break;
否则它将通过每个案例陈述,这就是为什么他们都被分配了该值