我創建幾個活動的應用程序的所有變量。 SharedPreferences在多個活動中讀取。Android的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);
我從來沒有見過這種事情發生。代碼在這裏真的很有幫助。 – 2012-01-09 20:35:17
你可以張貼代碼 – nandeesh 2012-01-09 20:36:00