The event handler in Fig. 4.21 calls MainActivity
method addTaggedSearch
(Fig. 4.23) to add a new search to savedSearches
or to modify an existing search.
111 // add new search to the save file, then refresh all Buttons
112 private void addTaggedSearch(String query, String tag)
113 {
114 // get a SharedPreferences.Editor to store new tag/query pair
115 SharedPreferences.Editor preferencesEditor = savedSearches.edit();
116 preferencesEditor.putString(tag, query); // store current search
117 preferencesEditor.apply(); // store the updated preferences
118
119 // if tag is new, add to and sort tags, then display updated list
120 if (!tags.contains(tag))
121 {
122 tags.add(tag); // add new tag
123 Collections.sort(tags, String.CASE_INSENSITIVE_ORDER);
124 adapter.notifyDataSetChanged(); // rebind tags to ListView
125 }
126 }
127
To change a SharedPreferences
object’s contents, you must first call its edit method to obtain a SharedPreferences.Editor
object (line 115), which can add key–value pairs to, remove key–value pairs from, and modify the value associated with a particular key in a SharedPreferences
file. Line 116 calls SharedPreferences.Editor
method putString to save the search’s tag (the key) and query (the corresponding value)—if the tag already exists in the SharedPreferences
this updates the value. Line 117 commits the changes by calling SharedPreferences.Editor
method apply to make the changes to the file.
When the user adds a new search, the ListView
should be updated to display it. Lines 120–125 determine whether a new tag was added. If so, lines 122–123 add the new search’s tag to tags
, then sort tags
. Line 124 calls the ArrayAdapter
’s notifyDataSetChanged method to indicate that the underlying data in tags has changed. The adapter then notifies the ListView
to update its list of displayed items.