To reset the settings for SharedPreferences in Android

I had a hard time to achieve to reset preferences back to their default values on Android development. So I would like to describe some caveats.

“setDefaultValues” ​​will set uninitialized parameters only

Description of the last parameter of “PreferenceManager#setDefaultValues” (readAgain) is as follows.

Whether to re-read the default values. If false, this method will set 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.

From this description, you may feel like that the preferences will be reseted back to their default values if you call the “setDefaultValues” by readAgain being true.
However, you can not do so by the following code only.

If you look again the description of “readAgain”, you will find following notes.

Note: this will NOT reset preferences back to their default values. For that functionality, use getDefaultSharedPreferences(Context) and clear it followed by a call to this method with this parameter set to true.

This means that “setDefaultValues” loads default values but not override parameters that has been set already. Only uninitialized parameters are read. So, you should clear parameters in advance.

Clear first, then call “setDefaultVallues”

Concretely, describe as follows.

Then, settings are reset to the default values.

However, if you run the above code while displaying the “PreferenceActivity”, they will not be redraw. You can not verify that the values has been changed before back from the activity and show it again.

To redraw the Activity

If you place the reset button in “PreferenceActivity”, thus UI is incomplete. So you need a way to redraw the “Activity”. As a result of my invesigation, I found that the method in java – refreshing views of Preferences when using PreferenceActivity – Stack Overflow works well.

Then, I found out more about “Activity#overridePendingTransition” in my own way and found that you should put it after “finish()” or “startActivity()”. In addition, testing the code, I made sure that it is unnecessary to specify “FLAG_ACTIVITY_NO_ANIMATION”.

After all, I confirmed that creating the following code as a method of “Activity” (in this article, “PreferenceActivity”) and calling it after “setDefaultValues” above will go well.

[Reference Sites]