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.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment. getDataDirectory() .
You can create a new shared preference file or access an existing one by calling one of these methods: getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from any Context in your app.
To clear all the values in the shared preferences file, call the clear() method on the shared preferences editor and apply the changes. SharedPreferences.
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE); String restoredText = prefs. getString("text", null); if (restoredText != null) { String name = prefs. getString("name", "No name defined");//"No name defined" is the default value.
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.
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