Android Preferences: How to Load the Default Values When the User Hasn't Used the Preferences-Screen

Android Preferences: How to load the default values when the user hasn't used the preferences-screen?

this question is similar to mine:

initialize-preferences-from-xml-in-main-activity

Just use this code in onCreate method:

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. That means setting the readAgain argument to false means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity is created

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

Android sharedPreferences set default values issue

You are receiving the default value itself, i.e, "error" because with Preferences, when you get the value of any preference then you need to specify a value that is to be returned if the preference is not set before. In your case, as you are setting the default value to "error" in here pref = sharedPrefs.getString("edit_text_pref", "error"); so thats what you get as the default value.

Initialize preferences from XML in the main Activity

In onCreate() of your main Activity just call the PreferenceManager.setDefaultValues() method.

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

This will read your preference.xml file and set the default values defined there. Setting the readAgain argument to false means this will only set the default values if this method has never been called in the past so you don't need to worry about overriding the user's settings each time your Activity is created.

Shared Preferences default value

You don't have to set them to be the same. Why the Android team at Google did not create an overloaded method that does not take a default value like getString(String key) is beyond me. If the values are different, you will get the value you set on android:defaultValue on your XML.

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

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.



Related Topics



Leave a reply



Submit