Android Coder: Retrieving Data on Background Threads with AsyncTask

When links are retrieved in NixMashupLinks for Android we can't simply use a getNixMashupLinks(uri) method in our LinkListFragment class. That would bring the application to a grinding halt until all of the links were loaded. Instead we'll retrieve the links on a background thread using a utility class called AsyncTask. AsyncTask does a lot of things, but all we need for it to do to get started is create our background thread and run our code in a doInBackground() method on that thread.

Here's our private FetchItemsTask class inside of LinkListFragment.java, showing the class declaration and our doInBackground() method.

To retrieve our NixMashup Links XML data file from the API Server we use

new FetchItemsTask().execute();

On the background thread we'll call the appropriate LinkFetchr() Java Class method to actually retrieve the list of links.

Returning Data from the Background Thread

Okay we can create a background thread and retrieve our links, but how do we pass them back to the main application thread?

First, let's look at the FetchItemsTask class declaration above once again. Notice the FetchItemsTask’s third generic parameter, ArrayList<NixMashupLink>. This parameter is the type of result produced by our AsyncTask. It is also what we input to a second method in FetchItemsTask, onPostExecute().

In onPostExecute() we are saving the retrieved XML link data in a serialized JSON file on the device. This saves a lot of trips to the server while the user moves throughout the application. Then in setupAdapter() we call our LinkAdapter (which extends ArrayAdapter<NixMashupLink>) to bind the NixMashupLink object to the individual Link List Fragment layouts.

Now that we covered a few of the functions of AsyncTask, here is another example in NixMashupLinks. The individual image bitmaps are retrieved and processed on their own background thread as well. This keeps the application zippy, with the only penalty being that the larger images may appear after the link textual content on slow connections.

Android Coder Notes for this Post

AsyncTask was implemented in NixMashupLinks from the initial Version 1.0.1 Branch in the repository.

Posted December 11, 2014 04:39 PM EST

More Like This Post