gpt4 book ai didi

Android:无法在 SharedPreferences 中保存 boolean 值

转载 作者:行者123 更新时间:2023-11-29 20:32:33 24 4
gpt4 key购买 nike

大家好,我无法使用 SharedPreferences 保存 boolean 值。由于某些原因,该值始终为真。这是我保存值的方式:

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 与从 prefs 读取时传递的不同。这将导致访问不同的共享首选项存储。如果您在不同的 Activity 中进行写入和读取并决定将 this 作为上下文传递,这将特别容易踩到。除非有这样做的理由,否则您很可能希望从应用中的任何位置访问您的首选项,然后始终使用应用程序上下文 (getApplicationContext())。

关于Android:无法在 SharedPreferences 中保存 boolean 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31750574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com