By Barry Burd

An AsyncTask is what you use when something takes too much time during the run of your Android app. For example, the user requests a web page. Who knows how long it takes to fetch the page? The service that hosts the web page might be experiencing high volume. Or the user might be on a train passing through a tunnel.

All kinds of things might slow down the page’s retrieval. And during this retrieval, the user might want to click buttons, scroll a document, or do something else that demands a response from your app.

You can’t stop the show while your app waits for a web page, fetches a Twitter timeline, or updates the user’s Twitter status. That’s why you code the network request inside an AsyncTask.

Android’s AsyncTask is versatile enough to deal with all types of values. In fact, the documentation defines an AsyncTask this way:

android.os.AsyncTask<Params,Progress,Result>

The definition has three generic type placeholders — Params, Progress, and Result. When you create your own AsyncTask, you “fill in the blanks” by specifying actual types in place of Params, Progress, and Result.

Posting a new tweet

To add a tweet on behalf of the user, you grab a Twitter object (the instance that you made with factory.getInstance()), and you call the instance’s updateStatus method. You don’t want this network request to interrupt the flow of your main activity, so you put the request inside an AsyncTask. The task’s name is MyAsyncTaskTweet. The task’s three generic types are as follows: String, Void, and String:

public class MyAsyncTaskTweet
extends AsyncTask&lt; String, Void, String> {
  • The first type ( String ) represents a 140-character tweet.

    The code

    execute(editTextTweet.getText().toString())

    grabs a string of characters from one of the activity’s text fields and passes that string to MyAsyncTaskTweet. Inside MyAsyncTaskTweet, the doInBackground method calls that string tweet[0] and uses that tweet[0] string to update the user’s status.

    The parameter to the updateStatus method is an array element. That’s because, in the doInBackground method’s header, tweet is a varargs parameter. The word varargs means “variable number of arguments.” You can pass as many values to doInBackground as you want. In the body of the method, you treat tweet as though it’s an ordinary array. The first tweet value is tweet[0]. If there were a second tweet value, it would be tweet[1], and so on.

  • The second type ( Void ) stands for a value (or values) that mark the background thread’s progress in completing its work.

    Since there is no progress indicator, the second type name is Void.

    In Java, the Void class is a wrapper class for the void value. Put that in your black hole of nothingness!

  • The third type ( String ) stands for a phrase such as Success! or Failed to tweet.

    The doInBackground method finds the string associated with either R.string.success, R.string.twitter_failure, or R.string.general_failure and returns this string as its result. Then the onPostExecute method displays this string in the screen’s editTextTweet field.

This image summarizes the way generic type names influence the methods’ types.

The use of types in MyAsyncTaskTweet.

The use of types in MyAsyncTaskTweet.

The image below summarizes how values move from one place to another in the MyAsyncTaskTweet.

The flow of values in MyAsyncTaskTweet.

The flow of values in MyAsyncTaskTweet.

Getting a user’s timeline

If you’ve seen one AsyncTask, you’ve seen ‘em all! The MyAsyncTaskTimeline class is almost identical to the MyAsyncTaskTweet. The only differences are as follows:

  • In MyAsyncTaskTweet, the parameter passed to doInBackground is treated as a tweet. But in MyAsyncTaskTimeline, the parameter passed to doInBackground is a username. The code passes this username to the getUserTimeline method.

  • In MyAsyncTaskTweet, the value returned from doInBackground is a success or failure message. But in MyAsyncTaskTimeline, the value returned from doInBackground is a string full of tweets (a timeline).

The code to fetch a user’s timeline looks something like this:

List<twitter4j.Status> statuses = null;
statuses = twitter.getUserTimeline(username[0]);

A fellow named Yusuke Yamamoto developed Twitter4J (or at least, Yusuke Yamamoto was the Twitter4J project leader), and at some point, Mr. Yamamoto decided that the getUserTimeline method returns a collection of twitter4J.Status objects. (Each twitter4J.Status instance contains one tweet.) So, to honor the contract set by calling the getUserTimeline method, the code declares statuses to be a collection of twitter4J.Status objects.

A few lines later in the code, an enhanced for statement steps through the collection of statuses values and appends each value’s text to a big result string. The loop adds n (Java’s go-to-the-next-line character) after each tweet for good measure. In the onPostExecute method, the code displays the big result string in the screen’s textViewTimeline field.

In the second doInBackground method, the fully qualified name twitter4j.Status is used. This is done to distinguish the twitter4J.Status class from Android’s own AsyncTask.Status class (an inner class of the AsyncTask class).

An AsyncTask can be fairly complicated. But when you compare Android’s AsyncTask to the do-it-yourself threading alternatives, the AsyncTask idea isn’t bad at all. In fact, when you get a little practice and create a few of your own AsyncTask classes, you get used to thinking that way. The whole business starts to feel quite natural.