What's Your Preference?
private SharedPreferences.OnSharedPreferenceChangeListener prefListener=
new SharedPreferences.OnSharedPreferenceChangeListener() {
public void onSharedPreferenceChanged(SharedPreferences sharedPrefs, String
key) {
if (key.equals("sort_order")) {
}
}
};
All we are doing right now is watching for our specific preference of interest
(sort_order), though we are not actually taking advantage of the changed
value.
Step #6: Re-Apply the Sort Order on Changes.................................
Finally, we actually need to change the sort order. For simple lists like this,
the easiest way to accomplish this is to get a fresh Cursor representing our
list (from getAll() on RestaurantHelper) with the proper sort order, and use
the new Cursor instead of the old one.
First, pull some of the list-population logic out of onCreate(), by
implementing an initList() method as follows:
private void initList() {
if (model!=null) {
stopManagingCursor(model);
model.close();
}
model=helper.getAll(prefs.getString("sort_order", "name"));
startManagingCursor(model);
adapter=new RestaurantAdapter(model);
setListAdapter(adapter);
}
Note that we call stopManagingCursor() so Android will ignore the old
Cursor, then we close it, before we get and apply the new Cursor. Of course,
we only do those things if there is an old Cursor.
The onCreate() method needs to change to take advantage of initList():