SharedPreferences 不会在 PreferenceActivity 中保存/加载

发布于 2024-11-17 08:13:35 字数 1424 浏览 6 评论 0原文

编辑: 下面描述的问题是由于非常特殊的设备问题引起的,而不是由任何编码相关问题引起的。

我有一个preferenceActivity,其中有很多checkBoxPreferences。 checkBoxPreference 应该保存默认的共享首选项文件,然后在我打开应用程序以更新 UI 时再次调用。

这并没有像想象的那样发生。 如果我关闭应用程序并重新打开它,我的值仍然像预期的那样,但如果我使用任务管理器结束应用程序或者如果我重新启动手机(当应用程序未运行时),则将调用 defaultValues再次。

因此,我在 onResume() 中创建了一个 SharedPreference 来测试它。

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

然后我检查该共享首选项中是否有密钥。

pref.contains("myCheckBoxPreference");

当我关闭并重新打开它时,它返回 true。如果我关闭任务管理器或关闭和打开手机电源,则返回 false。

因此,我尝试手动设置 SharedPreference

SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("myCheckBoxPreference", myCheckBoxPreference.isChecked());
editor.commit();

,然后在复选框首选项值更改时调用它。我还尝试在 onStop 和 onPause 中调用它。不过,如果我关闭应用程序并重新打开它, pref.contains 会返回 true,但如果我关闭手机然后重新打开,它会返回 false。

所以我然后尝试使用 SharedPreferences 文件。

在类声明中:

public static final String PREFS = "prefs";

在 onResume():

SharedPreferences pref = this.getSharedPreferences(PREFS, 0);

相同的行为中,如果我关闭应用程序并重新打开它, pref.contains 仍然返回 true,但如果我关闭手机然后重新打开,它会返回 false。

然后,我尝试将 myCheckBoxPreference 的键值更改为与 CheckBoxPreference 的 xml 键不匹配的值,但它仍然具有相同的效果。

我从手机上卸载了该应用程序,然后将手机关机并重新开机,然后重新安装,仍然具有相同的效果。

EDIT: The problem described below was due to a very peculiar device issue not caused by any coding-related problem.

I have a preferenceActivity in which I have many checkBoxPreferences.
The checkBoxPreference is suppose to save the the default shared preferences file, and then be called again when I open the app in order to update the UI.

This does not happen like it's suppose to.
If I close the app and open it back up, my values remain like they are suppose to, but if I use task manager to end the app or if I power cycle the phone (when the app is not running) then the defaultValues are called again.

So, I created a SharedPreference in my onResume() to test it.

SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

I then check to see if there is a key in that sharedpreference.

pref.contains("myCheckBoxPreference");

When I close out and open it back up, it returns true. if I close with the task manager or power cycle the phone off and on, then that returns false.

So, I tried manually setting the SharedPreference

SharedPreferences.Editor editor = pref.edit();
editor.putBoolean("myCheckBoxPreference", myCheckBoxPreference.isChecked());
editor.commit();

and then I called that when the checkboxpreference value changed. I also tried calling it in onStop and onPause. Still, if I close the app and open it back up, pref.contains returns true, but if I power cycle the phone off and back on, it returns false.

So I then tried using a SharedPreferences file.

In the class declaration:

public static final String PREFS = "prefs";

And in the onResume():

SharedPreferences pref = this.getSharedPreferences(PREFS, 0);

Same behavior, pref.contains still returns true if I just close the app and open it back up, but it returns false if I power the phone off and back on.

I then tried changing the key value of myCheckBoxPreference to something that did NOT match the xml key for the CheckBoxPreference, and it still had the same effect.

And I uninstalled the application from the phone, then powered the phone off and back on, and then re-installed, and it still has the same effect.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

画中仙 2024-11-24 08:13:35

我刚刚解决了,我很确定。我没有代码错误,我的应用程序没有任何问题(无论如何,我不相信。)

我创建了一个名为“testproj”的新项目,然后我从我的设置 PreferenceActivity 复制了所有代码,粘贴它到 TestprojActivity 中,我从它所依赖的 xml 中复制代码,然后将其粘贴到 TestProj 的 main.xml 中。

然后,我在 Samsung Captivate 上安装了 TestProj,更改了周围的设置,通过 RAM 管理(我拥有的自定义 ROM 的一项功能)清除了 RAM,然后设置卡住了。然后我重新启动手机,设置仍然存在,就像我配置它们一样。

当我使用以下命令手动设置它们时,它们都保持不变,

PreferenceManager.getDefaultSharedPreferences();

并且没有手动将它们保存到 SharedPreferences 中。

由于这不是我的手机,我还没有尝试过,但我认为恢复出厂设置可以完全修复它
编辑:我能够在新的三星 Captivate 和三星 Infuse 上进行测试,并且它有效。

我浪费了很多时间试图解决这个问题,我希望它对其他人有帮助。 :)

I just solved it, I'm pretty sure. There's no code error on my part, and there is no issue with my app whatsoever (I don't believe, anyway.)

I created a new project called "testproj", then I copied ALL the code from my settings PreferenceActivity, pasted it into the TestprojActivity, and I copied the code from the xml it relied on, then pasted that into the main.xml of TestProj.

I then installed TestProj on the Samsung Captivate, changed the settings around, cleared the ram through RAM management (a function of the custom ROM I have), and the settings stuck. I then power cycled the phone and the settings were still there like I'd configured them.

They stayed both when I manually set them using:

PreferenceManager.getDefaultSharedPreferences();

and without manually saving them to the SharedPreferences.

Since it is not my phone, I haven't tried it yet, but I assume a Factory Data reset would fix it completely
EDIT: I was able to test on both a new Samsung Captivate and a Samsung infuse, and it worked.

I wasted a lot of my time trying to figure this out, and I hope it helps someone else. :)

双马尾 2024-11-24 08:13:35

我在 Samsung Galaxy S 上遇到了可能类似的问题,其中首选项 XML 文件的权限已以某种方式更改/损坏。

日志显示某些主机进程无法读取该文件,导致所有设置重置为默认值。我不记得确切的错误消息,但它类似于“/path/to/preferences/file.xml 的权限被拒绝”。

我的解决方案是通过“设置”、“应用程序”、“管理应用程序”、“我的应用程序”、“删除数据”删除应用程序数据。这会删除与应用程序关联的首选项文件,问题立即消失。

我认为这是一个孤立的事件,因为我没有在各种 Android 设备(包括 Galaxy S II)上再次遇到过这种情况。

I encountered a possibly similar problem on a Samsung Galaxy S, where the permissions for the preferences XML file had somehow changed/corrupted.

The log revealed some host process was failing to read the file, causing all the settings to reset to their defaults. I don't recall the exact error message, but it was along the lines of "permission denied for /path/to/preferences/file.xml".

The resolution for me was to delete the application data through Settings, Applications, Manage Applications, MyApp, Delete data. This deletes the preference file associated with the app and the problem instantly disappeared.

I assumed it was an isolated event, as I've not run into it again on a variety of Android devices (including the Galaxy S II).

幸福还没到 2024-11-24 08:13:35

在客户的主要测试设备上,我遇到了同样的问题。使用的设备是具有 SDK 级别 8 (2.2.1) 的 Samsung Galaxy S。

奇怪的行为是,SharedPreferences 未保存,或者在恢复出厂设置后,它们太持久,也就是说,在重新安装应用程序后它们不会被删除。

由于当前发行 2.2.x,以及三星的数量Galaxy S 设备的销量已达数百万台,发生此问题的可能性很大

因此,实施保存首选项的解决方法可以被认为是至关重要的。

为了收集详细特征以明确地隔离此解决方法,每个也面临该问题的人都可以请提供相应的内核版本 (System.getProperty("os.version"< /code>)在这里?

我在想这样的事情:

// !! I know that 2.6.32.9 is not yet correct. This would be a false positive !!
if ((System.getProperty("os.version").startsWith("2.6.32.9"))
    && (android.os.Build.DEVICE.contains("GT-I9000")))
    useInternalStorage();
else
    useSharedPreferences();

一旦准备好并且有人感兴趣,我也可以在这里发布真正的代码。


编辑:一些附加信息:

面临该问题的设备问题:

    Property                         | Values
    ---------------------------------+------------------------------------
    Build.DEVICE                     | "GT-I9000T"
    Build.VERSION.INCREMENTAL        | "UBJP9"
    Build.VERSION.RELEASE            | "2.2.1"
    Build.VERSION.SDK                | 8
    System.getProperty("os.version") | "2.6.32.9"
    

类似设备不会面临该问题:

    Property                         | Values
    ---------------------------------+------------------------------------
    Build.DEVICE                     | "GT-I9000"
    Build.VERSION.INCREMENTAL        | "AOJP4"
    Build.VERSION.RELEASE            | "2.2"
    Build.VERSION.SDK                | 8
    System.getProperty("os.version") | "2.6.32.9"
    

On the client's main test device I came across the very same issue. The Device used is a Samsung Galaxy S with SDK level 8 (2.2.1).

The strange behavior is that either SharedPreferences are not saved, or, as after a factory reset, they're too persistent, that is to say they are not deleted after having reinstalled the application.

Due to the current distribution of 2.2.x, and the number of Samsung Galaxy S devices sold being several millions, the probability of an occurrence of this issue is significant.

So it can be considered as crucial to implement a workaround for saving preferences.

For collecting detailed characteristics to isolate this workaround in a sharp-edged way, could everyone who is also facing that issue please provide the corresponding kernel version (System.getProperty("os.version") here?

I was thinking of something like this:

// !! I know that 2.6.32.9 is not yet correct. This would be a false positive !!
if ((System.getProperty("os.version").startsWith("2.6.32.9"))
    && (android.os.Build.DEVICE.contains("GT-I9000")))
    useInternalStorage();
else
    useSharedPreferences();

I can post the real code here also once it's ready and someone is interested.


EDIT: some additional information:

Devices facing that issue:

    Property                         | Values
    ---------------------------------+------------------------------------
    Build.DEVICE                     | "GT-I9000T"
    Build.VERSION.INCREMENTAL        | "UBJP9"
    Build.VERSION.RELEASE            | "2.2.1"
    Build.VERSION.SDK                | 8
    System.getProperty("os.version") | "2.6.32.9"
    

Similar devices NOT facing that issue:

    Property                         | Values
    ---------------------------------+------------------------------------
    Build.DEVICE                     | "GT-I9000"
    Build.VERSION.INCREMENTAL        | "AOJP4"
    Build.VERSION.RELEASE            | "2.2"
    Build.VERSION.SDK                | 8
    System.getProperty("os.version") | "2.6.32.9"
    

爱给你人给你 2024-11-24 08:13:35

在设置值之前尝试清除编辑器。我遇到了同样的问题,它对我有用。
例子:

Editor e = PreferenceManager.getDefaultSharedPreferences(getParent()).edit();
e.clear();
e.putStringSet(key, value);

Try clearing the editor before you set your values. I had the same problem and it worked for me.
Example:

Editor e = PreferenceManager.getDefaultSharedPreferences(getParent()).edit();
e.clear();
e.putStringSet(key, value);
秋意浓 2024-11-24 08:13:35

可以通过使用sharedUserId来解决权限问题,它对于您的任何签名应用程序都应该相同。

http://developer.android.com/reference/android/R.attr .html#sharedUserId

It is possible to work around the issue of permissions by using sharedUserId which should be the same for any of your signed apps.

http://developer.android.com/reference/android/R.attr.html#sharedUserId

我不是你的备胎 2024-11-24 08:13:35

我也遇到了保存和检索数据的问题。我将保存和加载代码放在扩展应用程序的类中,因为我想要数据的单个实例。我可以看到字符串被保存,LogCat 中没有错误,但是当我尝试加载它时,再次没有错误,我的字符串是空的。我从未检查过数据是否实际进入文件,因此我不知道保存或加载是否失败或两者都失败。

我的代码或多或少如下:(comboToSave只是Gson从一个简单的数据类生成的字符串)

在一种方法中保存:

  SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); 
  SharedPreferences.Editor editor = sharedPref.edit();
  editor.putString(getString(R.string.prefCombos), comboToSave); 
  editor.commit();

在另一种方法中加载:

  SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
  String loadedComboText = sharedPref.getString(getString(R.string.prefCombos), "");

经过大量的绞尽脑汁并且不知道该怎么做后,我改变了 检索sharedPref 值的代码

SharedPreferences sharedPref = Activity.getPreferences(Context.MODE_PRIVATE);

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

这里还有更多内容关于两者之间的差异(尽管在我的情况下看起来完全相同),

但我的 Galaxy S3 上的结果是相同的。然而,在其他设备(包括 VD(虚拟设备))上测试这两个版本是有效的。

在代码的第一个版本中,我从调用活动传递了活动;用于从从用户收集最后一点数据的活动中保存,以及从我的主要活动中加载,以便在应用程序启动时我已准备好。

我昨晚尝试卸载应用程序并重新安装,关闭设备然后再次打开,但无济于事。

我现在已将保存和加载方法从应用程序类移至完成输入的活动,即加载和保存代码现在位于同一活动中。我已经用代码的两种变体对此进行了测试,并且它们都有效。我拿回我节省的东西。然后我将所有代码移回 Application 类并且它可以工作;这让我相信,通过所有的安装/卸载,我设法让它工作。 要点是:代码是正确的 - 如果它不起作用,则可能是设备和/或设置造成的

I too had a problem with saving and then retrieving data. I had my Save and Load code in a class that extends Application because I wanted a single instance of my data. I could see the String being saved, no errors in LogCat and yet when I try to load it, again with no error, my String is empty. I never checked whether the data actually went into the file so I have no idea whether there was a failure on Save or Load or both.

My code was more or less as follows: (comboToSave is simply a string generated by Gson from a simple data class)

in one method to save:

  SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE); 
  SharedPreferences.Editor editor = sharedPref.edit();
  editor.putString(getString(R.string.prefCombos), comboToSave); 
  editor.commit();

in another method to load:

  SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);
  String loadedComboText = sharedPref.getString(getString(R.string.prefCombos), "");

After lots of head scratching and not knowing what to do I changed the code that retrieves the sharedPref value from

SharedPreferences sharedPref = activity.getPreferences(Context.MODE_PRIVATE);

to

SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

There is some more here on the difference between the two (although in my case it seems exactly the same)

Still the result on my Galaxy S3 was the same. However, testing both versions on other devices, including VDs (virtual devices) worked.

In the first version of the code I passed the Activity from the calling activity; for save from the activity where the final bit of data is collected from the user, and for loading from my main activity so that I had it ready when the app is started.

I played with uninsalling the app and re-intalling, turning the device off and on again last night to no avail.

I have now moved the save and load methods from the application class to the activity where I complete the input i.e. both load and save code is now in the same activity. I have tested this with both variations of the code and they both work. I get back what I save. I then moved all the code back to the Application class and it works; this leads me to believe that somehow with all the installing/uninstalling I somehow managed to get it working. Point is: the code is correct - if it does not work the device and/or settings are probably to blame

人│生佛魔见 2024-11-24 08:13:35

我也遇到了同样的问题,困扰了一段时间,终于找到了解决方案,
这很简单,只需传递活动的直接引用,并且不使用任何通用上下文

public SessionManagment(Activity mContextActivity){
//  this.contextActivity = mContext;
    sharedPrefSession =  mContextActivity.getSharedPreferences(
            Constants.SHARED_PREFERANCES_LIGHT_TIGER_SESSION_FILE_NAME, 
            Context.MODE_PRIVATE);

}//enden constructor 

上面的代码是我为会话管理编写的类的构造函数,并且
当我在 AsyncTask 的主 ActivityFramgment 的代码中调用它时,我这样调用它

SessionManagment sessionManagment = new SessionManagment(referanct2thisActivity);

,其中referanct2thisActivity 在片段活动的“onCreate”函数中定义,

referanct2thisActivity = this;

希望将来能帮助其他人

I have the same problem, and i suffered from it for a while , finally i found the solution ,
and it is so easy , just pass the direct reference of the activity , and do not use any general context

public SessionManagment(Activity mContextActivity){
//  this.contextActivity = mContext;
    sharedPrefSession =  mContextActivity.getSharedPreferences(
            Constants.SHARED_PREFERANCES_LIGHT_TIGER_SESSION_FILE_NAME, 
            Context.MODE_PRIVATE);

}//enden constructor 

the code above is the constructor of the class that i have written for session management , and
and when i call it in the code in the main ActivityFramgment in a AsyncTask i call it like this

SessionManagment sessionManagment = new SessionManagment(referanct2thisActivity);

where referanct2thisActivity is defined in "onCreate" function of fragment activity like this

referanct2thisActivity = this;

hope that will help others in the future

隐诗 2024-11-24 08:13:35

有类似的问题。可能是因为重命名了包名称和项目名称。找到此线程后,我尝试更改首选项名称。例如:

SharedPreferences prefs = getSharedPreferences("myprefs", MODE_PRIVATE);

然后

SharedPreferences prefs = getSharedPreferences("mynewprefs", MODE_PRIVATE);

它又起作用了!

Had similar problem. Maybe because of renaming package name and project name. After finding this thread I tried to change the preferences name. For example:

SharedPreferences prefs = getSharedPreferences("myprefs", MODE_PRIVATE);

to

SharedPreferences prefs = getSharedPreferences("mynewprefs", MODE_PRIVATE);

then it worked again!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文