How to detect changes to your Android Preferences

This will demonstrate how to listen for changes to the user preferences in your app, so  that you can perform tasks depending on what the user selected/changed on the preferences screen.

I have an app, with a listfragment displaying rows of text. There is also a preferences screen (SettingsActivity.java) where users can set the sorting order of the list.

When users change the sort order, the list should be refreshed, to disaply the items in the new order.

This code is set up inside my listfragments onCreate() method.
(except the changedPrefsListener which is a field variable)

private SharedPreferences.OnSharedPreferenceChangeListener prefListener;

//listener on changed sort order preference:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());

prefListener = new SharedPreferences.OnSharedPreferenceChangeListener() {  
    public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {

        log("Settings key changed: " + key);
        if(key.equals(SettingsActivity.PREF_SORT_ORDER))
            getLoaderManager().restartLoader(LOADER_ID, null, tCallbacks);

    }
};
prefs.registerOnSharedPreferenceChangeListener(prefListener);  

The preferences.xml file looks like this:

<?xml version="1.0" encoding="utf-8"?>  
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

    <ListPreference
        android:key="pref_sort_order"
        android:title="Sort notes by"
        android:summary=""
        android:dialogTitle="Sort notes by"
        android:entries="@array/orderby_array_entries"
        android:entryValues="@array/orderby_array_values"
        android:defaultValue="edited" />

</PreferenceScreen>  

The preference listener allows me to detect that the PREFSORTORDER preference has been changed, so I can issue a restartLoader() call to refresh the list via the loadermanager.

In this case, the sort order of the list is changed, so the loader will have to do a new query against the Content Provider, with the right sort settings.

If you are sorting text, you have probably come across a problem where the sorting is case sensitive, to fix that, have a look at my previous post about case insensitive sorting.

comments powered by Disqus