Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset specific preferences Android

I've got a number of preferences that I want to reset back to the defaults specified in my preferences xml file.

I do not want to reset all of my preferences - just a few select ones.

I've tried:

key=getResources().getString(R.string.myPref);
sharedPreferences.edit().remove(key).commit();

This clears the preference. However when my program then tries to pick the preference up

String myPref = sharedPreferences.getString(key, "");

It just returns the empty string.

How do I get the value from the XML file?

Thanks

Adding more complete code sample that I've been debugging:

//Get preferences
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(activity);

//Get preference key
key=getResources().getString(R.string.myPref);

//Get preference value
String myPref = sharedPreferences.getString(key, ""); // Returns a value that has been entered by a user

//Clear preference
sharedPreferences.edit().remove(key).commit();

//Reset preferences to default values - without overwritting all
PreferenceManager.setDefaultValues(currentContext, preferences, false);

//Get preference value again
String myPref = sharedPreferences.getString(key, ""); // Returns an empty string
like image 582
Chris Nevill Avatar asked Mar 19 '26 07:03

Chris Nevill


2 Answers

Try PreferenceManager.setDefaultValues(this, R.xml.preferences, false); This is save as the last parameter ensures that user changed entries don't get overridden.

like image 64
Dan Avatar answered Mar 20 '26 21:03

Dan


getDefaultSharedPreferences(Context).setDefaultValues(this, R.xml.preference, true);

Be sure to set last argument readAgain to true.

This will force to re-read the default values. If false, this method sets the default values only if this method has never been called in the past (or if the KEY_HAS_SET_DEFAULT_VALUES in the default value shared preferences file is false). To attempt to set the default values again bypassing this check, set readAgain to true.

like image 45
Sander Versluys Avatar answered Mar 20 '26 19:03

Sander Versluys



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!