2014-06-18 15 views
1

值這裏是我把值碼:sharedpreferences不會記得在安卓

if(soundima == 1){ 
         soundima=0; 
         editor.putInt("sOn", soundima); 
         editor.commit(); 
        } 
        else if(soundima == 0){ 
         soundima=1; 
         editor.putInt("sOn", soundima); 
         editor.commit(); 
        } 

於是,當我退出程序,值不記得。我得到這個代碼的值:

editor = PreferenceManager.getDefaultSharedPreferences(this); 
    soundima = editor.getInt("sOn", 0); 
+0

你確定你的代碼去進入你的'if-else'語句的好處? –

+0

是的,絕對可以.. – user3330053

+0

你能告訴我們如何創建'編輯器'對象嗎? –

回答

3

我不完全確定爲什麼這是行不通的。但是,下面的代碼應該可以解決問題。

//create a constant to use for the shared preferences 
public static final String YOUR_CONSTANT = "Preferences"; 

然後放置值共享偏好,使用如下代碼:

if(soundima == 1){ 
    soundima = 0; 
    SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0); 
    SharedPreferences.Editor editor = sound.edit(); 
    editor.putInt("sOn", soundima); 
    editor.commit(); 
} 
else if(soundima == 0){ 
    soundima = 1; 
    SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0); 
    SharedPreferences.Editor editor = sound.edit(); 
    editor.putInt("sOn", soundima); 
    editor.commit(); 
} 

然後檢索值,使用此代碼:

SharedPreferences sound = getSharedPreferences(YOUR_CONSTANT,0); 
soundima = sound.getInt("sOn", 0); 
+0

這解決了我的問題,謝謝! :) – user3330053