Blog Archives

[TUTORIAL] Working in the background

In this tutorial we’ll talk some aspects that involves a mobile developer in many situations. In particular we’ll deepen concepts like threads (in particular AsyncTasks) and JSON parsing through Google GSON.

This slideshow requires JavaScript.

Before you start, take a look at:

Now you are ready to perform this simple steps:

  1. Take TWITTER_URL that you find in the project in AsyncTaskActivity
  2. Past it into JSONLint board and press Validate

In this way you’ll view if your JSON is valid and how it’s structured.

After that you need to create (there’s mine 😛 ) an android project in which you add into AndroidManifest.xml the internet permission and an Activity that’ll be your ListActivity implementation. It’s important to that because our application uses an Internet connection to contact Twitter servers. After that you need to prepare your xml layouts and resources: you’ll find them into res folder.

Now there is the core of your application that it’s related to code implementation and in particular to the AsyncTaskActivity and HTTPUtil that you can read in the attached project.

  • HTTPUtil: it’s a very simple utility class that performs a get request and returns the result as String
  • AsyncTaskActivity: it’s the ListActivity implementation that I have provided to allow you to download some tweets from Twitter and show them on screen

Into your ListActivity implementation to avoid to stop your main UI Thread we’ll implement the data fetching into a background Thread. That’s not a good practise but a must that grants to user a good experience and  to avoid “Your application has unexpectedly…. bla bla”. Hence, I have provide an implementation of AsyncTask that allows you to perform into the background the following operations:

  • contact Twitter servers
  • retrieve JSON response
  • parse response into a List of Tweets

In fact all these operations are performed into doInBackground(….) method. All those updates those involves UI, in our case list refresh, are done in the UI thread and for that are done in onPostExecute(…). Pay attention that if you perform these actions out of your main Thread you get a fatal error and your app crashes relentlessly. If you try this tutorial on your mobile phone or into emulator you’ll obtain the screens that you can see in the SlideShow.

The solution that I have provided is very simple and there are other mechanism that connected to data persistance grants to user a better UE (user-experience).

I hope that this tutorial will be very helpful,