Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make SharedPreferences from a PreferenceActivity be set to default in Android?

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.

like image 414
Gober Avatar asked Nov 30 '10 12:11

Gober


People also ask

Where are shared preferences stored Android?

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() .

How can I access SharedPreferences from another activity?

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.

What does the SharedPreferences editor Clear () method do?

To clear all the values in the shared preferences file, call the clear() method on the shared preferences editor and apply the changes. SharedPreferences.

How do you use SharedPreferences in Android to store fetch and edit values?

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.


1 Answers

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.

like image 174
Pentium10 Avatar answered Sep 20 '22 18:09

Pentium10