Sunday, December 1, 2013

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.

 public class MainActivity extends ListActivity {  
      protected void onCreate(Bundle savedInstanceState) {  

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

Webservice Type : REST 
Url :
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:

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

 package com.example.placesjson;  
 import java.util.List;  
 public class GeonameList {  
      private List<Geonames> geonames;  
      public List<Geonames> getGeonames() {  
           return this.geonames;  
      public void setGeonames(List<Geonames> geonames) {  
           this.geonames = geonames;  

 package com.example.placesjson;  
 public class Geonames {  
      private String countrycode;  
      private String fcl;  
      private String fclName;  
      private String fcode;  
      private String fcodeName;  
      private Number geonameId;  
      private Number lat;  
      private Number lng;  
      private String name;  
      private Number population;  
      private String toponymName;  
      private String wikipedia;  
      [... getters and setters]  

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.

 private void callService() {  
      // Show a loading dialog.  
      dialog =, "Loading", "Calling GeoNames web service...", true, false);  
      // Create the thread that calls the webservice.  
      Thread loader = new Thread() {  
           public void run() {  
                // init stuff.  
                cities = new GeonameList();  
                boolean error = false;  
                // build the webservice URL from parameters.  
                String wsUrl = "";  
                wsUrl += "&north="+COORD_N;  
                wsUrl += "&south="+COORD_S;  
                wsUrl += "&east="+COORD_E;  
                wsUrl += "&west="+COORD_W;  
                String wsResponse = "";  
                try {  
                     // call the service via HTTP.  
                     wsResponse = readStringFromUrl(wsUrl);  
                     // deserialize the JSON response to the cities objects.  
                     cities = new Gson().fromJson(wsResponse, GeonameList.class);  
                catch (IOException e) {  
                     // IO exception  
                     Log.e(TAG, e.getMessage(), e);  
                     error = true;  
                catch (IllegalStateException ise) {  
                     // Illegal state: maybe the service returned an empty string.  
                     Log.e(TAG, ise.getMessage(), ise);  
                     error = true;  
                catch (JsonSyntaxException jse) {  
                     // JSON syntax is wrong. This could be quite bad.  
                     Log.e(TAG, jse.getMessage(), jse);  
                     error = true;  
                if (error) {  
                     // error: notify the error to the handler.  
                else {  
                     // everything ok: tell the handler to show cities list.  
      // start the thread.  

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.

 // This handler will be notified when the service has responded.  
 final Handler handler = new Handler() {  
      public void handleMessage(Message msg) {  
           if (msg.what == CODE_ERROR) {  
                Toast.makeText(MainActivity.this, "Service error.", Toast.LENGTH_SHORT).show();  
           else if (cities != null && cities.getGeonames() != null) {  
                Log.i(TAG, "Cities found: " + cities.getGeonames().size());  

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

 private void buildList() {  
      // init stuff.  
      List<Map<String, String>> data = new ArrayList<Map<String, String>>();  
      Map<String, String> currentChildMap = null;  
      String line1;  
      String line2;  
      // cycle on the cities and create list entries.  
      for (Geonames city : cities.getGeonames()) {  
           currentChildMap = new HashMap<String, String>();  
           line1 = city.getToponymName() + " (" + city.getCountrycode() + ")";  
           line2 = "Population: " + city.getPopulation();  
           currentChildMap.put("LABEL", line1);  
           currentChildMap.put("TEXT", line2);  
      // create the list adapter from the created map.  
      adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2,   
                new String[] { "LABEL", "TEXT" },  
                new int[] {, });  

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

 protected void onCreate(Bundle savedInstanceState) {  

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-

{"status":{"message":"user does not exist.","value":10}}

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.


    Very useful ... thx for download!


  2. Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.Android Training in chennai |Android Training in Velachery

  3. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.Android Training institute in chennai with placement | Best Android Training in velachery

  4. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website
    full Stack developer Training in Bangalore

  5. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Click here:
    python training in tambaram
    Click here:
    python training in annanagar

  6. I appreciate your efforts because it conveys the message of what you are trying to say. It's a great skill to make even the person who doesn't know about the subject could able to understand the subject . Your blogs are understandable and also elaborately described. I hope to read more and more interesting articles from your blog. All the best.
    Blueprism training in velachery

    Blueprism training in marathahalli

    AWS Training in chennai

  7. Have you been thinking about the power sources and the tiles whom use blocks I wanted to thank you for this great read!! I definitely enjoyed every little bit of it and I have you bookmarked to check out the new stuff you post

  8. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this

    java training in annanagar | java training in chennai

    java training in marathahalli | java training in btm layout

  9. I was recommended this web site by means of my cousin. I am now not certain whether this post is written through him as nobody else recognise such precise about my difficulty. You're amazing! Thank you!

    angularjs Training in bangalore

    angularjs Training in btm

    angularjs Training in electronic-city

    angularjs online Training

    angularjs Training in marathahalli

  10. Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
    python training in velachery | python training institute in chennai

  11. In the beginning, I would like to thank you much about this great post. Its very useful and helpful for anyone looking for tips. I like your writing style and I hope you will keep doing this good working.
    Angularjs Training Institute in Bangalore
    Angularjs Classes in Bangalore
    Angularjs Coaching in Bangalore
    Best ccna Institute in Bangalore
    ccna Institute in Bangalore

  12. Wonderful piece of work. Master stroke. I have become a fan of your words. Pls keep on writing.


  13. Thank you for taking the time to provide us with your valuable information. We strive to provide our candidates with excellent care and we take your comments to heart.As always, we appreciate your confidence and trust in us
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training


  14. Just seen your Article, it amazed me and surpised me with god thoughts that eveyone will benefit from it. It is really a very informative post for all those budding entreprenuers planning to take advantage of post for business expansions. You always share such a wonderful articlewhich helps us to gain knowledge .Thanks for sharing such a wonderful article, It will be deinitely helpful and fruitful article.

  15. Thanks for sharing this great article. It made me understand few things about this concept which I never knew before. Keep posting such great articles so that I gain from it. Java Training in Chennai | J2EE Training in Chennai | Advanced Java Training in Chennai | Core Java Training in Chennai | Java Training institute in Chennai


  16. This is a fantastic idea! I like it a lot because it's super easy for the audience to see the value of opting in. wonderful and amazing post very use full your post thanks for sharing your article
    Android Application development
    Web application

  17. This is a fantastic idea! I like it a lot because it's super easy for the audience to see the value of opting in. wonderful and amazing post very use full your post thanks for sharing your article
    Android Application development
    Web application

  18. Your post is very good. I got to learn a lot from your post. Thank you for sharing your article for us. it is amazing post
    what is seo
    types of seo

  19. Your info is really amazing with impressive content..Excellent blog with informative concept. Really I feel happy to see this useful blog, Thanks for sharing such a nice blog..
    If you are looking for any Big data Hadoop Related information please visit our website hadoop classes in pune page!

  20. Thank you for shairing this information about how a Android app that retrieves data from a JSON webservice.
    big data training in btm
    Big data training institute in btm layout

  21. Thanks for sharing your innovative ideas to our vision. I have read your blog and I gathered some new information through your blog. Your blog is really very informative and unique. Keep posting like this. Awaiting for your further update.If you are looking for any Big Data related information, please visit our website Big Data training institute in Bangalore.

  22. Do you want to get back love of your life and have tried all possible efforts but failed in all? Did you love someone madly but recently had a breakup? Do you want your beloved back? If yes then astrology is the best which recommends various remedies to solve this problem.

    Get your love back astrologer to see a wonderful difference created in your love life. Astrology will work like magic and at the end your love life will be blessed with happiness and passion for each other. Ask your World Famous Indian Astrologer now.

  23. This is a very helpful blog..
    Thanks for sharing with us,
    We are again come on your website,
    Thanks and good day,
    Please visit our site,

  24. Usually I never comment on blogs but your article is so convincing that I never stop myself to say something about it. You’re doing a great job,Keep it up.

    Try Our BLACK MAGIC REMOVAL EXPERT IN TORONTO Services and Get All the benefits of it in your life, we make All your Personal problems solved in just minutes.

  25. This is excellent information. It is amazing and wonderful to visit your site.Thanks for sharng this information,this is useful to me.
    AWS training in chennai | AWS training in annanagar | AWS training in omr | AWS training in porur | AWS training in tambaram | AWS training in velachery