Android: 无法在 SharedPreferences 中保存布尔值

Android: Unbale to save boolean in SharedPreferences

大家好,我无法使用 SharedPreferences 保存布尔值。由于某些原因,该值始终为真。以下是我如何保存值:

public static void setSharedPreference(Context ctx, String keyValue, boolean value){
    SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putBoolean(keyValue,value);
    editor.commit();
}

这就是我取回它的方式:

 public static boolean getBooleanPreference(Context ctx, String keyValue){
    boolean prefValue;
    SharedPreferences sp = ctx.getSharedPreferences(Constants._preferencesName, ctx.MODE_PRIVATE);
    prefValue = sp.getBoolean(keyValue, false);

    return prefValue;
}

怎么了?!

您的代码在语法上是正确的,但我怀疑您在保存时传递的 Context 与从首选项读取时传递的不同。这将导致访问 不同的 共享首选项存储。如果您在不同的活动中进行写入和读取并决定将 this 作为上下文传递,这将特别容易踩到。除非有理由这样做,否则您很可能希望从应用程序中的任何位置访问您的首选项,然后始终使用应用程序上下文 (getApplicationContext())。

您的代码中的一切都是正确的。

只有 出错的可能性是在调用这些方法时。放入和检索数据时请使用 getApplicationContext()

请为应用程序执行“清除数据”并从干净的 SharedPreference 开始。