Where should you name PreferenceManager.setDefaultValues?

To initialize the settings with the default values ​​from the XML file that describes the settings, I can call PreferenceManager.setDefaultValues(this, R.xml.preference, false). It sounds simple, but I'm not quite sure when exactly should I call it?

As I understand from the documents, the aforementioned call is needed only once, in a situation where the settings are not yet set. As a result of this call, the preferences that are in will be configured /data/data/<myapp>/shared_prefs, so all subsequent attempts to read the settings will receive default values. Logically, setDefaultValuesit should be called in each separate code path that can be executed without preferences already initialized. Over time, this turned out to be several places - the main activity, another action, background service, small BroadcastReceiverprocessing of system messages ... Right now I put a call setDefaultValuesin onCreate()for my application object, since I already use it as a convenient singleton for other things.

Questions:

  • Do I have a guarantee that every time my code is executed, an application object will be created and onCreate will be launched?
  • How do you deal with this problem? Another way would be to convert the default values ​​to getFoo(key, defValue), but this effectively dissipates your default settings for all the code.

EDIT . In fact, I don’t know which solution is worse: a call setDefaultValuesevery time I access the files in a given code path or call it in some common place (for example, app onCreate) every time, regardless of whether I need it or no.

+5
source share
1 answer

.

  • , onCreate . , , , . Android , (, ). , , , , .
  • , SharedPreferences ( MyPrefs - , , ). MyPrefs:
    • get/set
    • . , AtomicBoolean, , .

, ... , , SharedPreferences , , , , .

, , .

+2

All Articles