Android Java Sharedpreferences 不会保存数据

Android Java Sharedpreferences won't save data

在我 "saved" 一个字符串之后它将 return (在我的例子中)"error": html_value1 不是“”

主要活动:

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

报警服务活动:

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

我该如何解决这个问题?

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

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

主要活动:

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

如果使用 apply() 就更好了。此方法returns直接,后台保存数据,不阻塞线程。