您应该在哪里调用 PreferenceManager.setDefaultValues?
为了使用描述首选项的 XML 文件中的默认值初始化首选项,我可以调用 PreferenceManager.setDefaultValues(this, R.xml.preference, false)。听起来很简单,但我不太确定我到底应该什么时候调用它?
据我从文档中了解到,在尚未设置首选项的情况下,上述调用只需要一次。作为此调用的结果,将设置驻留在 /data/data/
中的首选项,因此所有后续读取首选项的尝试都将获得默认值。从逻辑上讲,应该在每个可能在未初始化首选项的情况下执行的代码路径中调用 setDefaultValues。随着时间的推移,这变成了多个地方 - 主活动、另一个活动、后台服务、处理系统消息的小型 BroadcastReceiver
...现在我已经调用了 setDefaultValues
> 在我的 Application 对象的 onCreate()
中,因为我已经将它用作其他事物的方便单例。
问题:
- 我是否能保证每次执行代码时,都会创建 Application 对象并且 onCreate 将运行?
- 你是如何处理这个问题的?另一种方法是将默认值硬编码到 getFoo(key, defValue) 调用中,但这会有效地将默认设置分散到整个代码中。
编辑:本质上,我不知道哪种解决方案更糟糕:每次访问给定代码路径中的首选项时调用 setDefaultValues
,或者在某个常见位置调用它(例如应用程序的onCreate) 每次,无论我是否需要它。
In order to initialize preferences with default values from XML file describing the preferences, I can call PreferenceManager.setDefaultValues(this, R.xml.preference, false)
. Sounds simple, but I'm not quite sure when exactly should I call this?
As I understand from the docs, the above call is only needed once, in situation when no preferences are set yet. As a result of this call, preferences residing in /data/data/<myapp>/shared_prefs
are going to be set, so all subsequent attempts to read preferences will get me the default values. Logically, setDefaultValues
should be called in every single code path that might be executed without preferences being already initialized. Over time, this turned out to be multiple places - main activity, another activity, background service, small BroadcastReceiver
handling system messages... Right now I've put call to setDefaultValues
in onCreate()
for my Application object, as I'm already using it as convenient singleton for other things.
Questions:
- Do I have a guarantee that every time my code executes, Application object will be created and onCreate will run?
- How are you dealing with this problem? One other way would be to hardcode default values into
getFoo(key, defValue)
calls, but that effectively scatters your default settings across whole code.
EDIT: Essentially, I don't know which solution is worse: calling setDefaultValues
every time I access prefs in given code path, or calling it in some common place (like app's onCreate) every time, no matter whether I need it or not.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将删除原来的答案并回答您实际提出的问题。
话虽如此......它对我有用,但如果您几乎可以肯定,每次您的代码在您所在的位置运行时,您都会调用 SharedPreferences 。
希望这比我之前的答案更有帮助。
I'm going to delete my original answer and answer the questions that you actually asked.
MyPrefs
-- that's not what I call it but that's not important). The key features of MyPrefs are:Having said that... it works for me, but if you're almost certain you'll be calling the SharedPreferences every time your code runs where you're at works as good as any.
Hope this helps more than my previous answer.