Handling the Background Processing

Now it is time to identify what processing should run asynchronously. For this example, it is the downloading and parsing code. You override the doInBackground() method, which is where all the background processing takes place. The methods called within doInBackground() will not block the main UI thread. Here's a sample implementation of the doInBackground() method, with exception handling removed for clarity: ©Override protected Boolean doInBackground(Object... params) { boolean result = false; String pathToScores = (String) params[0]; table = (TableLayout) params[1]; XmlPullParser scores = null; URL xmlUrl = new URL(pathToScores);

scores = XmlPullParserFactory.newInstance().newPullParser(); scores.setInput(xmlUrl.openStream(), null); if (scores != null) {


return result;

Here you simply generate the appropriate URL to the application server and use the openStream() method to access the data stream from a remote application server.

After you call the setInput() method of the XmlPullParser, you can use that XmlPullParser just as you used the one pointed at local resource data.

Now move the processScores() method into the ScoreDownloaderTask class. Now you will want to update the method, which simply takes the XmlPullParser and parses the XML, to publish scores as they are parsed, using the publishProgress() method:

private void processScores(XmlPullParser scores) throws XmlPullParserException, IOException { int eventType = -1; boolean bFoundScores = false;

// Find Score records from XML

while (eventType != XmlResourceParser.END_DOCUMENT) { if (eventType == XmlResourceParser.START_TAG) {

// Get the name of the tag (eg scores or score) String strName = scores.getName();

if (strName.equals("score")) { bFoundScores = true; String scoreValue =

scores.getAttributeValue(null, "score"); String scoreRank =

scores.getAttributeValue(null, "rank"); String scoreUserName =

scores.getAttributeValue(null, "username"); publishProgress(scoreValue, scoreRank, scoreUserName);

eventType = scores.next();

// Handle no scores available if (bFoundScores == false) { publishProgress();

The publishProgress() method can be called anytime within the doInBackground() method to cause the onProgressUpdate() callback method to be called. This allows the background process to communicate with the UI thread.

Was this article helpful?

0 0

Post a comment