Search code examples
androidandroid-preferencespreferenceactivity

SharedPreferences not saved using PreferenceActivity


I'm trying to create a very basic preferences activity, extending PreferenceActivity. In the documentation, I read:

The PreferenceActivity automatically persists the settings associated with each Preference when the user makes a change.

However, when I:

  • Change a setting (any setting)
  • Close the app
  • Remove the app from the recently used list
  • Relaunch the app

The setting is reset to the default value, which seems to conflict the quoted documentation above. Do I misunderstand something here, is the template faulty, or do I perhaps need additional permissions or other settings to use the PreferenceActivity auto-persist feature?

public class SettingsActivity extends PreferenceActivity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction()
                .replace(android.R.id.content, new SettingsFragment()).commit();
    }

    public static class SettingsFragment extends PreferenceFragment {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
        }
    }
}

And preferences.xml:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <ListPreference
        android:key="pref_language_reading"
        android:title="@string/pref_title_language_dailyreading"
        android:entries="@array/pref_languages_dailyreading_entries"
        android:entryValues="@array/pref_languages_dailyreading_values"
        android:defaultValue="@string/pref_language_dailyreading_default" 
        android:persistent="true" />
</PreferenceScreen>

The strings and arrays exist, and I can select a language properly. The setting is saved when I go to another activity, and then back. But closing the app and relaunching discards the saved value.

When I read out the SharedPreference corresponding to this preference (before relaunching), I see the correct setting. After relaunching, the SharedPreference does not exist anymore though.


Solution

  • The code should work. There is likely something else in your code that causes this behaviour.

    In my specific case, it turned out there was a line

    PreferenceManager.getDefaultSharedPreferences(this).edit().clear().commit();
    

    In the onCreate() method of the main Activity, causing the SharedPreferences to clear on every launch of the app.