简体   繁体   English

我希望我的布尔值在共享首选项中保存为真,但它总是保存为假

[英]I am expecting my boolean to be saved in shared preferences as true, however it always saves as false

I am trying to save a boolean into shared preferences with a value of true but when I log it I keeping seeing it returning a false value.我试图将一个布尔值保存到值为 true 的共享首选项中,但是当我记录它时,我一直看到它返回一个 false 值。 Please see the code below and also bear in mind that this code is within a fragment.请参阅下面的代码,并记住此代码在一个片段中。

 SharedPreferences AppPreferences = getActivity().getSharedPreferences("myPrefs", Activity.MODE_PRIVATE);
      boolean propertyManagerLoggedIn = AppPreferences.getBoolean(PROPERTYMANAGER_LOGGEDIN, false);

      if(!propertyManagerLoggedIn)
      {
         SharedPreferences.Editor editor = AppPreferences.edit();
         transitionInterface.showDashboardIcons();
         AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
         editor.commit();
         //boolean vlaue = prefs.getbooleanflag(context, false);
         Log.d("tag",""+propertyManagerLoggedIn);

      }
     else
      {

         Log.d("tag",""+propertyManagerLoggedIn);
      }

and below is the relevant lines of code from my AppPreferences class下面是来自我的 AppPreferences 类的相关代码行

 public final static String PROPERTYMANAGER_LOGGEDIN = "PROPERTYMANAGER_LOGGEDIN";

  public static boolean propertyManagerLoggedn(Context context)
   {
      TinyDB settings = new TinyDB(context);
      return settings.getBoolean(AppPreferences.PROPERTYMANAGER_LOGGEDIN);
   }

every time you call edit() a new Editor is being returned to you.每次您调用edit()都会向您返回一个新的Editor Accordingly to the documentation根据文档

Create a new Editor for these preferences, through which you can make modifications to the data in the preferences and atomically commit those changes back to the SharedPreferences object.为这些首选项创建一个新的编辑器,您可以通过它修改首选项中的数据并将这些更改自动提交回 SharedPreferences 对象。

so you can either do所以你可以这样做

AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true).commit();

or或者

 editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
 editor.commit();

but calling putBoolean on an instance and commit on an other won't probably help但是在一个实例上调用putBoolean在另一个实例上commit可能无济于事

You are calling commit on a different instance.您正在不同的实例上调用 commit。 Basically AppPreferences.edit() will give you a new instance.基本上AppPreferences.edit()会给你一个新的实例。

AppPreferences.edit().putBoolean("PROPERTYMANAGER_LOGGEDIN", true);

This is another instance in which you are putting the boolean value.这是您放置布尔值的另一个实例。

Use the same instance which you have created.使用您创建的相同实例。 Your code should look like this:您的代码应如下所示:

SharedPreferences.Editor editor = AppPreferences.edit();
         transitionInterface.showDashboardIcons();
         editor.putBoolean("PROPERTYMANAGER_LOGGEDIN", true);
         editor.commit();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM