【问题标题】:Preference not being removed across all contexts偏好不会在所有情况下都被删除
【发布时间】:2017-04-19 18:46:45
【问题描述】:

我有一个看起来像这样的偏好 Util 类:

public class PreferenceUtils {
    public static SharedPreferences getSharedPreferences(final Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context);
    }

    public static String getToken(final Context context) {
        SharedPreferences sp = getSharedPreferences(context);
        return sp.getString("TOKEN", null);
    }

    public static void setToken(final Context context, final String token) {
        SharedPreferences sp = getSharedPreferences(context);
        sp.edit().putString("TOKEN", token).apply();
    }
}

问题是,如果我尝试从一个上下文中删除“TOKEN”首选项(例如MainActivity):

SharedPreferences prefs = PreferenceUtils.getSharedPreferences(context);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("TOKEN");
editor.apply();

如果我从不同的上下文(例如UserActivity)调用它,它仍然存在。

如何在整个应用中删除 TOKEN 首选项?我应该在 Util 类中以不同的方式处理我的偏好吗?

【问题讨论】:

  • 您的代码看起来不错。您可以尝试提交而不是应用吗?
  • 提交结果相同。 ://

标签: android android-activity sharedpreferences android-preferences


【解决方案1】:

试试这个:

editor.putString("TOKEN", "");
editor.commit();

【讨论】:

    【解决方案2】:

    尝试像这样修改您的 getSharedPreferences 方法:

    public static SharedPreferences getSharedPreferences(final Context context) {
        return PreferenceManager.getDefaultSharedPreferences(context.getApplicationContext());
    }
    

    目前,您正在获得不同上下文的共享偏好,因此可能会导致问题。

    【讨论】:

      猜你喜欢
      • 2020-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多