Suppose that I have an application which saves preferences onto two files, preferences1.xml and preferences2.xml. Then, I can retrieve references to the corresponding objects with the following code:
SharedPreferences sharedPrefs1 = getSharedPreferences("preferences1", MODE_PRIVATE);
SharedPreferences sharedPrefs2 = getSharedPreferences("preferences2", MODE_PRIVATE);
In this way I can manipulate the preferences for both and register listeners for changes on both.
I have some doubts about the initialization of those two files, with setDefaultValues:
Question 1 - PreferenceFragment context: I've created a PreferenceActivity with two PreferenceFragments and within the onCreate method of each one I execute the following code (replace X with 1 and 2 for fragment 1 and 2):
PreferenceManager pm = getPreferenceManager();
pm.setSharedPreferencesName("preferencesX");
PreferenceManager.setDefaultValues(getActivity(),R.xml.preference_fragmentX, false);
I've seen that both fragments correctly set their preferences with their default values when launched.. but, given the fact that I can see only a single _has_set_default_values.xml file in the shared_prefs directory of the app, how does it understand when properties of preferences1.xml and preferences2.xml have been already set? This file is created as soon as setDefaultValues is called in the first opened PreferenceFragment, but even after that, if I open the second PreferenceFragment it correctly initializes default values. How does it understand that it has not yet initialized preferences2.xml and what is the purpose of _has_set_default_values.xml given the fact that it does not contains information about which prefereces files have been initialized?
Question 2 - Standard Activity context: when I start my app, the PreferenceActivity is not the first activity started and the user may never open it, so I'd like to initialize the two preference files with their default values also in the main Activity, how can I do that? For default shared preferences it is easy:
PreferenceManager.setDefaultValues(this, R.xml.default_preferences, false);
For two preference files how should I do? I can not do something like the following since I can not retrieve an instance of PreferenceManager like in the PreferenceFragment classes:
PreferenceManager pm = getPreferenceManager(); // NOT AVAILABLE AND NOT WANTED
pm.setSharedPreferencesName("preferences1");
PreferenceManager.setDefaultValues(getActivity(),R.xml.preference_fragment1, false);
PreferenceManager pm = getPreferenceManager(); // NOT AVAILABLE AND NOT WANTED
pm.setSharedPreferencesName("preferences2");
PreferenceManager.setDefaultValues(getActivity(),R.xml.preference_fragment2, false);
Here in the main Activity I do not have the need to change the preference files on which the PreferenceManager will work, since we're not in a PreferenceActivity, I simply want to initialize those two files... any help? I hope I've posted a clear question, even if too long.