Using AsyncTask to Run on a Background Thread

The next step is to call and test the networking code you just added. However, you cannot simply call FlickrFetchr.getUrlString(String) directly in PhotoGalleryFragment. Instead, you need to create a background thread and run your code there.

The easiest way to work with a background thread is with a utility class called AsyncTask. AsyncTask creates a background thread for you and runs the code in the doInBackground(…) method on that thread.

In PhotoGalleryFragment.java, add a new inner class called FetchItemsTask at the bottom of PhotoGalleryFragment. Override AsyncTask.doInBackground(…) to get data from a website and log it.

Listing 23.5  Writing an AsyncTask, part I (PhotoGalleryFragment.java ...

Get Android Programming: The Big Nerd Ranch Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.