2013-09-22 62 views
0

我有,我正在採取SharedPrefs的值和1每次創建程序時增加它一個非常簡單的活動。因此,當我打開和關閉(退出)程序時,我預計這會不斷增加。但是,它看起來像值不存儲。每次更改後我都使用提交。SharedPreferences不節能,甚至後提交

public class SharedPreferencesActivity extends Activity { 
/** Called when the activity is first created. */ 

public static final String PREFERENCE_FILENAME = "MyGamePreferences"; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    int int_out = 0; 
    SharedPreferences gameSettings = getSharedPreferences(PREFERENCE_FILENAME, MODE_PRIVATE); 
    SharedPreferences.Editor prefEditor = gameSettings.edit(); 

    int_out = gameSettings.getInt("Username", 0); 
    Log.e("Pre",Integer.toString(int_out)); 
    int_out = int_out + 1; 
    Log.e("During",Integer.toString(int_out)); 
    prefEditor.putInt("UserName", int_out); 
    prefEditor.commit(); 
    int_out = gameSettings.getInt("Username", 0); 

    Log.e("Post",Integer.toString(int_out)); 

} 
} 

上述我的代碼從Log.e statments輸出是

預:0 期間:1 發表:999

因此它似乎是後

calling prefEditor.commit(); 
int_out = gameSettings.getInt("Username", 0); 

SharedPref gameSettings未保存。

回答

2

你使用大寫字母一個密鑰。更改線路

prefEditor.putInt("UserName", int_out); 

prefEditor.putInt("Username", int_out); 
+0

哇感謝我錯過了莫名其妙 –