Retrieving data from a JSON webservice in Android - simple tutorial

In this guide I'll show how to write a basic Android app that retrieves data from a JSON webservice, and simply shows it in a list.

We'll be using the following stuff.

Create a new Android project, with a MainActivity class inside. Create a "libs" folder inside the project, and put the GSON jar in there. When you refresh the project, Eclipse should automatically add the jar to the project's build path.

Let's have our activity extend ListActivity instead of Activity.

Now let's look at the "citiesJSON" webservice API.

Webservice Type : REST
Url : api.geonames.org/citiesJSON?
Parameters :
north,south,east,west : coordinates of bounding box
callback : name of javascript function (optional parameter)
lang : language of placenames and wikipedia urls (default = en)
maxRows : maximal number of rows returned (default = 10)
Result : returns a list of cities and placenames in the bounding box, ordered by relevancy (capital/population). Placenames close together are filterered out and only the larger name is included in the resulting list.

We'll call the webservice with the 4 coordinates parameters. The webservice also requires an "username" parameter. You can use the "pimentoso" user for this test, or you can register your own username here: http://www.geonames.org/login

Go to the JSONgen website, and paste the sample URL for the webservice. When you hit "generate", the website will have you download a zip file containing the generated classes. Unzip the file and copy the classes in your project. The classes will look like this

Now we're gonna work on the activity. We're going to create the "callService()" method that does the main job: starting a thread that calls the webservice, and deserialize the data. The comments in the code should be self-explanatory.

The code contains the "readStringFromUrl()" utility method which is not covered in this guide. Please download the project zip at the end of this post to grab the code.

When the thread has completed, the "cities" object shoud contain data returned from the webservice. This is the simple handler that's called at the end of the method.

The last thing that remains is to actually populate the list, so let's write the "buildList()" method.

Let's wrap it all up, by calling "callService()" when the activity is started.

The final result should be something like this. Error handling

You will notice that when the webservice returns an error, a JsonSyntaxException is not actually thrown. This is because GSON only throws the exception if your class has a field whose type didn't match what is in the JSON. So, in case of an error like this-
The exception is not actually thrown. So if you want to retrieve the error message, you could expand your GeonameList class to contain a Status object, so GSON can fill it when it is returned.
You can read more about it here-

Other libraries

If GSON is a bit too heavy for you (with its almost 200KB) you can look into JSONbeans, a lighter library by EsotericSoftware.

You can get the project on Github.

Alternatively, you can download the Eclipse project ZIP here.
[null, {"document_url": "http://pimentoso.blogspot.com/2013/12/retrieving-data-from-json-webservice-in.html", "unformatted_src": "http://1.bp.blogspot.com/-fZ2zT_BmQF0/UpsRnIw8I8I/AAAAAAAACEw/tFHUH0tTooo/s400/Screen+Shot+2013-12-01+at+11.06.50+AM.png", "src": "http://1.bp.blogspot.com/-fZ2zT_BmQF0/UpsRnIw8I8I/AAAAAAAACEw/tFHUH0tTooo/s400/Screen+Shot+2013-12-01+at+11.06.50+AM.png", "formatted_filename": "Screen Shot   at", "rendered_width": 400, "rendered_height": 240}, null, {"document_url": "http://pimentoso.blogspot.com/2013/12/retrieving-data-from-json-webservice-in.html", "unformatted_src": "http://4.bp.blogspot.com/-d4qL7MT_Zww/UpsVrWp5ZKI/AAAAAAAACE8/mpJh7A7ksGE/s400/Screen+Shot+2013-12-01+at+11.54.29+AM.png", "src": "http://4.bp.blogspot.com/-d4qL7MT_Zww/UpsVrWp5ZKI/AAAAAAAACE8/mpJh7A7ksGE/s400/Screen+Shot+2013-12-01+at+11.54.29+AM.png", "formatted_filename": "Screen Shot   at", "rendered_width": 400, "rendered_height": 245}, null, {"document_url": "http://pimentoso.blogspot.com/2013/12/retrieving-data-from-json-webservice-in.html", "unformatted_src": "http://1.bp.blogspot.com/-ssWRteKspq8/UpsYFRfpCcI/AAAAAAAACFI/2Z7Dx-DCjVI/s400/device-2013-12-01-111108.png", "src": "http://1.bp.blogspot.com/-ssWRteKspq8/UpsYFRfpCcI/AAAAAAAACFI/2Z7Dx-DCjVI/s400/device-2013-12-01-111108.png", "formatted_filename": "device", "rendered_width": 240, "rendered_height": 400}, null, null, null, null, null, null, null]