What's Your Preference?
Then, we need to get our hands on our SharedPreferences instance. Add
imports to LunchList for android.content.SharedPreferences and
android.preference.PreferenceManager, along with a SharedPreferences data
member named prefs.
Next, add this line near the top of onCreate() in LunchList, to initialize prefs
to be the SharedPreferences our preference activity uses:
prefs=PreferenceManager.getDefaultSharedPreferences(this);
Finally, change the call to getAll() to use the SharedPreferences:
model=helper.getAll(prefs.getString("sort_order", "name"));
Here, we use name as the default value, so if the user has not specified a sort
order yet, the sort order will be by name.
Now, if you recompile and reinstall the application, then set a sort order
preference, you can see that preference take effect if you exit and reopen
the application.
Step #5: Listen for Preference Changes.............................................
That works, but users will get annoyed if they have to exit the application
just to get their preference choice to take effect. To change the sort order on
the fly, we first need to know when they change the sort order.
SharedPreferences has the notion of a preference listener object, to be
notified on such changes. To take advantage of this, add the following line
at the end of onCreate() in LunchList:
prefs.registerOnSharedPreferenceChangeListener(prefListener);
This snippet refers to a prefListener object, so add the following code to
LunchList to create a stub implementation of that object: