Question

I am working on implementing the preferences for our application. I know how to display preferences UI and how to read/write values using SharedPreferences. In our app, I need to handle two sets of preferences and I would like to ask about this issue, one comment in the Android documents in particular.

The documentation for Preference.getSharedPreferences() has the following comment under the Return values section:

Returns The SharedPreferences where this Preference reads its value(s), or null if it isn't attached to a Preference hierarchy.

I would like to ask how it is possible to attach a SharedPreferences to a particular Preference, be it EditTextPreference or others. In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?

To explain my question further with an example, suppose I have the following:

SharedPreferences prefs1 = getSharedPreferences(file1, mode);
SharedPreferences prefs2 = getSharedPreferences(file2, mode);

My question is what API I should use so that prefs1 is used by the Preference objects' persistence code and not prefs2.

The target is Nexus One, running 2.3.4.

Maybe the answer is obvious but I could not find it after reading the documentation and searching the web. Thank you in advance for your help.

Was it helpful?

Solution

In other words, how does the persistence code in a Preference know that it should store the user input in one particular SharedPreferences object and not the other?

Preference uses PreferenceManager's getSharedPreferences(), which eventually routes to getDefaultSharedPreferences().

You are welcome to create your own Preference subclasses that change this behavior, but since the preference screen system may not be designed to handle multiple SharedPreference objects, there's a chance that your preference changes might not get persisted.

IOW, I encourage you to reconsider:

In our app, I need to handle two sets of preferences

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top