2016-04-26 53 views
0

「錯誤」: html_value1不是 「」的Android的Java Sharedpreferences將不保存數據

MainActivity:

tools.getEditor(tools.getPreferences(getApplicationContext())).putString("wochea9a", html_value1); 
tools.getEditor(tools.getPreferences(getApplicationContext())).putString("wocheb9a", html_value2); 
tools.getEditor(tools.getPreferences(getApplicationContext())).commit(); 

Alarmserviceactivity:

savedwochea9a = tools.getPreferences(getApplicationContext()).getString("wochea9a", "error"); 
     savedwocheb9a = tools.getPreferences(getApplicationContext()).getString("wocheb9a", "error"); 

工具:

public class tools { 


    static SharedPreferences preferences; 
    static SharedPreferences.Editor editor; 




    public static SharedPreferences getPreferences(Context context){ 
     preferences = PreferenceManager.getDefaultSharedPreferences(context); 
     return preferences; 
    } 
    public static SharedPreferences.Editor getEditor(SharedPreferences preferences){ 
     editor = preferences.edit(); 

     return editor; 
    } 
... 

我該如何解決這個問題?

回答

3

每次創建編輯器時(使用edit()),必須調用commit()apply()以保存結果。

所以,你的代碼應該是這樣的:

MainActivity:

tools.getEditor(tools.getPreferences(getApplicationContext())) 
    .putString("wochea9a", html_value1) 
    .putString("wocheb9a", html_value2) 
    .commit(); // or .apply(); 

更妙的是,如果你使用apply()。此方法立即返回,將數據保存在後臺而不阻塞線程。