【问题标题】:Shared Pref returning wrong value in some high end devices like samsungShared Pref 在一些高端设备(如三星)中返回错误值
【发布时间】:2017-02-21 07:09:18
【问题描述】:

下面是我创建共享首选项的代码

public SaveData(Context con) {
    this.context = con;
    emailSharedPreferences = context.getSharedPreferences(KEY_PREF_EMAIL, Context.MODE_PRIVATE);
    emailEdit = emailSharedPreferences.edit();
}

用于设置数据

public void setData(boolean accepted) {
    emailEdit = emailSharedPreferences.edit();
    emailEdit.putBoolean(KEY, accepted);
    emailEdit.apply();
}

获取数据

public Boolean getData() {
    emailSharedPreferences = context.getSharedPreferences(KEY_PREF_EMAIL, Context.MODE_PRIVATE);
    return emailSharedPreferences.getBoolean(KEY, false);
}

当我尝试获取数据时,在我的应用程序启动器屏幕上,它在某些设备中返回“true”。

现在,如果我通过以下代码创建了共享首选项

 private static SharedPreferences getPreferences(Context context) {
   // return context.getSharedPreferences(PREF_NAME, MODE);
    return  PreferenceManager.getDefaultSharedPreferences(context);

}

private static SharedPreferences.Editor getEditor(Context context) {
    return getPreferences(context).edit();
}

对于集合数据

public static void setData(Context context,boolean value){
    try {
        getEditor(context).putBoolean(KEY, value).commit();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

获取数据

 public static boolean getData(Context context){
    try {
        return getPreferences(context).getBoolean(KEY, false);
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

现在它在所有设备上都可以正常工作。 有人能解释一下为什么会这样吗?

【问题讨论】:

  • 使用 commit() 时,数据立即写入存储,使用 apply() 时,仅写入缓存。
  • 我同时使用了提交和应用。但不适合我

标签: android android-sharedpreferences


【解决方案1】:

使用这个

emailEdit.commit();

之后

emailEdit.putBoolean(KEY, 接受);

【讨论】:

    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2014-10-29
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    相关资源
    最近更新 更多