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:
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With