Downloading Lots of Small Things

Currently, PhotoGallery’s networking works like this: PhotoGalleryFragment executes an AsyncTask that retrieves the JSON from Flickr on a background thread and parses the JSON into an array of GalleryItems. Each GalleryItem now has a URL where a thumbnail-size photo lives.

The next step is to go and get those thumbnails. You might think that this additional networking code could simply be added to FetchItemsTask’s doInBackground(…) method. Your GalleryItem array has 100 URLs to download from. You would download the images one after another until you had all 100. When onPostExecute(…) executed, they would be displayed en masse in the RecyclerView.

However, downloading the thumbnails all at once causes two problems. The first is that it could take a while, and the UI would not be updated until the downloading was complete. On a slow connection, users would be staring at a wall of Bills for a long time.

The second problem is the cost of having to store the entire set of images. One hundred thumbnails will fit into memory easily. But what if it were 1,000? What if you wanted to implement infinite scrolling? Eventually, you would run out of space.

Given these problems, real-world apps often download images only when they need to be displayed onscreen. Downloading on demand puts the responsibility on the RecyclerView and its adapter. The adapter triggers the image downloading as part of its onBindViewHolder(…) implementation.

AsyncTask is the easiest way to get a background thread, but it is ill-suited for repetitive and long-running work. (You can read why in the section called For the More Curious: AsyncTasks vs Threads at the end of this chapter.)

Instead of using an AsyncTask, you are going to create a dedicated background thread. This is the most common way to implement downloading on an as-needed basis.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.250.114