Downloading and Displaying Scores

Now let's work through a simple example of using AsyncTask within the QuizSettingsActivity class to handle the downloading and parsing of XML score information. You begin by creating a subclass called ScoreDownloaderTask, which extends the AsyncTask class within the QuizSettingsActivity class:

private class ScoreDownloaderTask extends AsyncTask<Object, String, Boolean> { // TODO: Implement AsyncTask callback methods TableLayout table;

Because you will be populating a TableLayout control as part of this background task, it makes sense to add a handy member variable within ScoreDownloaderTask as well.

Starting ScoreDownloaderTask

After you've implemented the ScoreDownloaderTask class, you will want to update the onCreate() method of the QuizScoresActivity class to call the ScoreDownloaderTask class's execute() method when the screen first loads. The execute() method takes two parameters: the server web address and the table to populate with scores (a TableLayout control):

public static final String TRIVIA_SERVER_BASE =

""; public static final String TRIVIA_SERVER_SCORES =

TRIVIA_SERVER_BASE + "scores.jsp"; // ...

allScoresDownloader =

new ScoreDownloaderTask(); allScoresDownloader.execute(TRIVIA_SERVER_SCORES, allScoresTable);

SharedPreferences prefs =

getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE); Integer playerId = prefs.getInt(GAME_PREFERENCES_PLAYER_ID, -1);

friendScoresDownloader = new ScoreDownloaderTask(); friendScoresDownloader.execute(

TRIVIA_SERVER_SCORES + "?playerId=" + playerId, friendScoresTable);

Now that you have set up the ScoreDownloaderTask class, you can focus on implementing the AsyncTask callback methods appropriately.

Don't worry about the playerId value just yet. We'll discuss that next hour.

Was this article helpful?

0 0

Post a comment