Android Java Sharedpreferences不会保存数据

时间:2016-04-26 14:57:48

标签: java android save sharedpreferences saving-data

我"保存"它将返回一个字符串(在我的例子中)"错误":   html_value1不是""

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;
    }
...

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:3)

每次创建编辑器(使用edit())时,您都必须调用commit()apply()才能保存结果。

因此,您的代码应如下所示:

<强> MainActivity:

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

如果使用apply(),情况会更好。此方法立即返回,将数据保存在后台而不会阻塞线程。