2016-04-26 28 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()。此方法立即返回,将数据保存在后台而不阻塞线程。