Question

I have created a PreferenceActivity based on xml for PreferenceScreen. In the xml you can assign default values to the different preferences. But these are not stored in my SharedPreferences before the screen is opened and closed.

The problem is that I want to immediately use the Preferences stored in this screen (like server address), and the user will only need to open it if he wants to change the default values.

Is there a way to store all the preferences from the preferencescreen xml without forcing the user to open and close the preference activity?

I am aware that you can supply a default value when retrieving the Preference from SharedPreferences, but it is stupid to have to maintain default values both in xml and code.

Was it helpful?

Solution

Just use this code in the Application class.

PreferenceManager.setDefaultValues(this, R.xml.preference, false);

It will load your preferences from XML, and last parameter (readAgain) will guarantee that user preferences won't be overwritten. You need to maintain the default parameters in the R.xml.preference file.

Take a look into PreferenceManager.setDefaultValues in Android API for further investigation.

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