Reset defaults for preferences

I am using CheckBoxPreference for the settings screen. XML:

<?xml version="1.0" encoding="utf-8"?> <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" > <CheckBoxPreference android:key="includeAddress" android:title="Include Address" android:summary="" android:defaultValue="true" /> <CheckBoxPreference android:key="rememberName" android:title="Remeber Name" android:summary="" android:defaultValue="false" /> </PreferenceScreen> 

I am changing the values ​​in the application. When the user logs out, he must be set to the default values, as defined in xml. But it doesn't seem to work. They store the values ​​that I last selected.

After reading the Android docs, I found the following:

 PreferenceManager.setDefaultValues(getApplicationContext(), R.xml.preference_settings, true); 

But it is unlikely to work! Tried a different way using SharedPreferences.

 SharedPreferences preferences = getParent().getSharedPreferences("preference_settings", MODE_PRIVATE); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); 

That didn't work either!

Am I missing something? How can I set the default preferences defined in XML?

Thanks in advance!

+7
source share
1 answer

general settings should work, but you should use general default settings.

 SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); SharedPreferences.Editor editor = preferences.edit(); editor.clear(); editor.commit(); 

To get general settings using a file name, Android creates that name (perhaps based on the package name of your project?). You can get it by putting the following code in ConfigurationActivity onCreate and looking at what preferencesName is.

 String preferencesName = this.getPreferenceManager().getSharedPreferencesName(); 

The string should be something like "com.example.projectname_preferences". Hard code somewhere in your project and pass it to getSharedPreferences (), and you should be good to go.

AS:

  PreferenceManager.getDefaultSharedPreferences(this); 

Provides access to the settings file, which is global for the entire application package; any activity can access preferences (internaly, an xml file containing preferences will be called your.application.package_preferences.xml ).

 getParent().getSharedPreferences("preference_settings", MODE_PRIVATE); 

Provides preferences only for the contextInstance class: only instances of the context class can access these settings (said that your package is still your.application.package , and you are in your.application.package.SecondActivity , internaly is the SecondActivity.xml settings SecondActivity.xml ).

+6
source

All Articles