Simple Persistence with Shared Preferences
Last, but not least, update FetchItemsTask to use the stored query rather than a hardcoded string. Add
a custom constructor to FetchItemsTask that accepts a query string as input and stashes it in a member
variable. In updateItems(), pull the stored query from shared preferences and use it to create a new
instance of FetchItemsTask. All of these changes are shown in Listing 27.14.
Listing 27.14 Using stored query in FetchItemsTask
(PhotoGalleryFragment.java)
public class PhotoGalleryFragment extends Fragment {
...
private void updateItems() {
String query = QueryPreferences.getStoredQuery(getActivity());
new FetchItemsTask(query).execute();
}
...
private class FetchItemsTask extends AsyncTask<Void,Void,List
private String mQuery;
public FetchItemsTask(String query) {
mQuery = query;
}
@Override
protected List
String query = "robot"; // Just for testing
if (querymQuery == null) {
return new FlickrFetchr().fetchRecentPhotos();
} else {
return new FlickrFetchr().searchPhotos(querymQuery);
}
}
@Override
protected void onPostExecute(List
mItems = items;
setupAdapter();
}
}
}
Search should now work like a charm. Run PhotoGallery, try searching for something, and see what
you get.