Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1
Simple Persistence with Shared Preferences

Getting a value you previously stored is as simple as calling SharedPreferences.getString(...),
getInt(...), or whichever method is appropriate for your data type. The second input to
SharedPreferences.getString(PREF_SEARCH_QUERY, null) specifies the default return value that
should be used if there is no entry for the PREF_SEARCH_QUERY key.


The setStoredQuery(Context) method writes the input query to the default shared preferences
for the given context. In your code above, you call SharedPreferences.edit() to get an
instance of SharedPreferences.Editor. This is the class you use to stash values in your
SharedPreferences. It allows you to group sets of changes together in transactions, much like you do
with FragmentTransaction. If you have a lot of changes, this will allow you to group them together
into a single storage write operation.


Once you are done making all of your changes, you call apply() on your editor to make them visible
to other users of that SharedPreferences file. The apply() method makes the change in memory
immediately and then does the actual file writing on a background thread.


QueryPreferences is your entire persistence engine for PhotoGallery. Now that you have a way to
easily store and access the user’s most recent query, update PhotoGalleryFragment to read and write
the query as necessary.


First, update the stored query whenever the user submits a new query.


Listing 27.12  Storing submitted query in shared preferences


(PhotoGalleryFragment.java)


public class PhotoGalleryFragment extends Fragment {
...
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater menuInflater) {
...
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String s) {
Log.d(TAG, "QueryTextSubmit: " + s);
QueryPreferences.setStoredQuery(getActivity(), s);
updateItems();
return true;
}


@Override
public boolean onQueryTextChange(String s) {
Log.d(TAG, "QueryTextChange: " + s);
return false;
}
});
}
...
}

Free download pdf