简体   繁体   English

SharedPerferences似乎不起作用

[英]SharedPerferences doesn't seem to be working

I'm trying to use SharedPreferences in my app but it just doesn't seem to be working. 我正在尝试在我的应用程序中使用SharedPreferences,但似乎无法正常工作。

First, I declare SharedPreferences as a global variable in the activity where I'm planning to use them: 首先,我在打算使用SharedPreferences的活动中将其声明为全局变量:

SharedPreferences prefs;

Then I set the default SharedPreferences in onCreate: 然后在onCreate中设置默认的SharedPreferences:

prefs = getSharedPreferences("urnikSp", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schudeleDownloaded", false);
editor.commit();

I then change the boolean value when a certain action is completed: 然后,当某个操作完成时,我将更改布尔值:

prefs.edit().putBoolean("schudeleDownloaded", true).commit();

And then in the same activity (when it is restarted), I check for the boolean value in onCreate like this: 然后在同一活动中(重新启动时),我像这样检查onCreate中的布尔值:

boolean schudeleDownloaded = prefs.getBoolean("schudeleDownloaded", false);
if (!schudeleDownloaded){
    new PopulateDatabase().execute();
}

And even though I clearly set the new value to "true" upon completing a certain action, the IF statement you see above still executes because the boolean value still seems to be false. 即使我在完成某些操作后将新值明确设置为“ true”,您在上面看到的IF语句仍然会执行,因为布尔值似乎仍然是false。

What am I doing wrong? 我究竟做错了什么?

Let me do a wild guess. 让我大胆地猜测。 Because when you restart, you set it to false again.... It is in onCreate function. 因为当您重新启动时,您再次将其设置为false。...它在onCreate函数中。

如果您正在重新创建活动,则将再次调用onCreate()方法,因此我认为您将其值改回false

You have to create a separate SharedPreferences.Editor instance. 您必须创建一个单独的SharedPreferences.Editor实例。 So instead of doing this: 所以不要这样做:

prefs.edit().putBoolean("schudeleDownloaded", true).commit();

Try this: 尝试这个:

SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("schedeleDownloaded", true);
editor.commit();

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

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