Chapter 25 HTTP and Background Tasks
Now you need to call setupAdapter() after data has been fetched from Flickr. Your first instinct might
be to call setupAdapter() at the end of FetchItemsTask’s doInBackground(...). This is not a good
idea. Remember that you have two Flashes in the store now – one helping multiple customers, and one
on the phone with Flickr. What will happen if the second Flash tries to help customers after hanging up
the phone? Odds are good that the two Flashes will step on each other’s toes.
On a computer, this toe-stepping-on results in objects in memory becoming corrupted. Because of this,
you are not allowed to update the UI from a background thread, nor is it safe or advisable to do so.
What to do? AsyncTask has another method you can override called onPostExecute(...).
onPostExecute(...) is run after doInBackground(...) completes. More importantly, onPostExecute(...)
is run on the main thread, not the background thread, so it is safe to update the UI within it.
Modify FetchItemsTask to update mItems and call setupAdapter() after fetching your photos to
update the RecyclerView’s data source.
Listing 25.17 Adding adapter update code (PhotoGalleryFragment.java)
private class FetchItemsTask extends AsyncTask<Void,Void,Void List
@Override
protected Void List
return new FlickrFetchr().fetchItems();
return null;
}
@Override
protected void onPostExecute(List
mItems = items;
setupAdapter();
}
}
You made three changes here. First, you changed the type of the FetchItemsTask’s third generic
parameter. This parameter is the type of result produced by your AsyncTask. It sets the type of value
returned by doInBackground(...) as well as the type of onPostExecute(...)’s input parameter.
Second, you modified doInBackground(...) to return your list of GalleryItems. By doing this you fixed
your code so that it compiles properly. You also passed your list of items off so that it can be used from
within onPostExecute(...).
Finally, you added an implementation of onPostExecute(...). This method accepts as input the list you
fetched and returned inside doInBackground(...), puts it in mItems, and updates your RecyclerView’s
adapter.
With that, your work for this chapter is complete. Run PhotoGallery, and you should see text displayed
for each GalleryItem you downloaded (similar to Figure 25.2).