Android JSON Parsing with JSONObject and loading to ListView – Example

September 10, 2012

In this article, we will create an Android application which will parse JSON data stored a local String variable and load to a ListView widget. The parsing process will be done in a non-ui thread using AsyncTask, one of the simplest method provided by Android to create multiple threads in an application.

This application is developed in Eclipse ( 4.2.0 ) with ADT plugin ( 20.0.3 ) and Android SDK ( R20.0.3 )

1. Create a new Android application project namely “ListViewWithJSON”

Create a new Android application project

Figure 1 : Create a new Android application project

2. Design application launcher icon

Design application launcher icon

Figure 2 : Design application launcher icon

3. Create a blank activity to define MainActivity class

Create a blank activity

Figure 3 : Create a blank activity

4. Enter MainActivity details

Enter MainActivity Details

Figure 4 : Enter MainActivity Details

5. Delete Android’s Support library from this project, if exists

By default Eclipse ( 4.2.0) adds Android Support Library to  Android application project. For this application, we don’t need to use this support library. So the library file libs/android-support-v4.jar may be removed manually via ProjectExplorer by simply right click on the file and then clicking the menu item “delete”.

6. Update the file res/values/strings.xml


    <string name="app_name">ListViewWithJSON</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">JSON Parser Demo</string>
    <string name="str_iv_flag">Flag</string>


7. Update the layout of MainActivity in the file res/layout/activity_main.xml

<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

        tools:context=".MainActivity" />

8. Create a custom layout for the ListView in the file res/layout/lv_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""
    android:layout_height="match_parent" >

        android:textStyle="bold" />

        android:contentDescription="@string/str_iv_flag" />

        android:layout_below="@id/tv_country" />


9. Create a class namely CountryJSONParser in the file src/in/wptrafficanalyzer/listviewwithjson/

package in.wptrafficanalyzer.listviewwithjson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class CountryJSONParser {

    /** Receives a JSONObject and returns a list */
    public List<HashMap<String,String>> parse(JSONObject jObject){

        JSONArray jCountries = null;
        try {
            /** Retrieves all the elements in the 'countries' array */
            jCountries = jObject.getJSONArray("countries");
        } catch (JSONException e) {
        /** Invoking getCountries with the array of json object
        * where each json object represent a country
        return getCountries(jCountries);

    private List<HashMap<String, String>> getCountries(JSONArray jCountries){
        int countryCount = jCountries.length();
        List<HashMap<String, String>> countryList = new ArrayList<HashMap<String,String>>();
        HashMap<String, String> country = null;

        /** Taking each country, parses and adds to list object */
        for(int i=0; i<countryCount;i++){
            try {
                /** Call getCountry with country JSON object to parse the country */
                country = getCountry((JSONObject)jCountries.get(i));
            } catch (JSONException e) {

        return countryList;

    /** Parsing the Country JSON object */
    private HashMap<String, String> getCountry(JSONObject jCountry){

        HashMap<String, String> country = new HashMap<String, String>();
        String countryName = "";
        String flag="";
        String language = "";
        String capital = "";
        String currencyCode = "";
        String currencyName = "";

        try {
            countryName = jCountry.getString("countryname");
            flag = jCountry.getString("flag");
            language = jCountry.getString("language");
            capital = jCountry.getString("capital");
            currencyCode = jCountry.getJSONObject("currency").getString("code");
            currencyName = jCountry.getJSONObject("currency").getString("currencyname");

            String details =        "Language : " + language + "\n" +
                                    "Capital : " + capital + "\n" +
                                    "Currency : " + currencyName + "(" + currencyCode + ")";

            country.put("country", countryName);
            country.put("flag", flag);
            country.put("details", details);

        } catch (JSONException e) {
        return country;

10. Update the class MainActivity in the file src/in/wptrafficanalyzer/listviewwithjson/

package in.wptrafficanalyzer.listviewwithjson;

import java.util.HashMap;
import java.util.List;

import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class MainActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        String strJson =
                        "{ " +
                            " \"countries\":[ " +

                                "{" +
                                    "\"countryname\": \"India\","+
                                    "\"flag\": "+ R.drawable.india + ","+
                                    "\"language\": \"Hindi\","+
                                    "\"capital\": \"New Delhi\"," +
                                    "\"currency\": {" +
                                        "\"code\": \"INR\", " +
                                        "\"currencyname\": \"Rupee\" " +
                                    "}" +
                                "}, " +

                                "{" +
                                    "\"countryname\": \"Pakistan\","+
                                    "\"flag\": "+ R.drawable.pakistan + ","+
                                    "\"language\": \"Urdu\","+
                                    "\"capital\": \"Islamabad\"," +
                                    "\"currency\": {" +
                                        "\"code\": \"PKR\", " +
                                        "\"currencyname\": \"Pakistani Rupee\" " +
                                    "}" +
                                "}," +

                                "{" +
                                    "\"countryname\": \"Sri Lanka\","+
                                    "\"flag\": "+ R.drawable.srilanka + ","+
                                    "\"language\": \"Sinhala\","+
                                    "\"capital\": \"Sri Jayawardenapura Kotte\"," +
                                    "\"currency\": {" +
                                        "\"code\": \"SKR\", " +
                                        "\"currencyname\": \"Sri Lankan Rupee\" " +
                                    "}" +
                                "}" +

                            "]" +
                        "} ";

        /** The parsing of the xml data is done in a non-ui thread */
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

        /** Start parsing xml data */

    private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

        JSONObject jObject;
        /** Doing the parsing of xml data in a non-ui thread */
        protected SimpleAdapter doInBackground(String... strJson) {
                jObject = new JSONObject(strJson[0]);
                CountryJSONParser countryJsonParser = new CountryJSONParser();
            }catch(Exception e){
                Log.d("JSON Exception1",e.toString());

            CountryJSONParser countryJsonParser = new CountryJSONParser();

            List<HashMap<String, String>> countries = null;

                /** Getting the parsed data as a List construct */
                countries = countryJsonParser.parse(jObject);
            }catch(Exception e){

            /** Keys used in Hashmap */
            String[] from = { "country","flag","details"};

            /** Ids of views in listview_layout */
            int[] to = {,,};

            /** Instantiating an adapter to store each items
            *  R.layout.listview_layout defines the layout of each item
            SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

            return adapter;

        /** Invoked by the Android system on "doInBackground" is executed completely */
        /** This will be executed in ui thread */
        protected void onPostExecute(SimpleAdapter adapter) {

            /** Getting a reference to listview of main.xml layout file */
            ListView listView = ( ListView ) findViewById(;

            /** Setting the adapter containing the country list to listview */

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(, menu);
        return true;

11. Screenshot of the application

Screenshot of the application in execution

Figure 5 : Screenshot of the application in execution

12. Download

13. Reference

How to hire me?

I am George Mathew, working as software architect and Android app developer at

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to

My other blogs

Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :

Tags: , , , , , , ,

17 Responses to Android JSON Parsing with JSONObject and loading to ListView – Example

  1. deepuag on October 16, 2012 at 10:12 am


  2. ejaz on November 1, 2012 at 3:19 pm

    how I put toggle Button in this Listview like your this example Enabling Multi Selection mode in ListView by adding ToggleButton using custom layout in Android

  3. Gloria on November 1, 2012 at 8:41 pm

    Hi, i have done something similar, but it throws an exception. at main,saying that my simpleAdapter is null. How can i fix it, i have been struggling with it for days now


    • george on November 1, 2012 at 10:00 pm

      You may have committed some bug in parse function which converts JSON object to the list object. This list object is later passed to the constructor of the SimpleAdapter class.

  4. Deepika Kadam on December 12, 2012 at 1:15 pm

    How to get all records of tv_country in MainActivity Class.
    Is it possible? plz help.
    Thank you!

  5. Nadir on January 17, 2013 at 10:30 am

    Thanx a lot dude…

  6. hussein on February 22, 2013 at 3:13 am

    Nice post, but can anyone please help me to modify this code that will opens a new activity when I click each item in the list view.

  7. TERET_PORT on April 28, 2013 at 4:33 pm

    Thanks for the cool tutorial! But could you do this code was changed so that the item is in bits and pieces there are two more buttons and when clicked, which would be called different things, thanks in advance, really looking forward to.

  8. Abdul Rokim on May 17, 2013 at 8:23 am

    Thanks for the great tutorial!

    I’ve succeed to perform asynctask in listview to one listfragment. Then, I want to use it in other listfragment with same process. So, this asynctask is reusable. How can I do? Thanks in advance.

  9. Kabelash on August 19, 2013 at 4:15 pm

    Hi, i have a JSON file something like this:
    “shops”: [
    "id": "11",
    "name": "Next",
    "description": "Opened in 2005, offers a selection of clothes, shoes and accessories.",
    "url": "/shop/550/127",
    "categories": [
    “bg_image”: “/uploads/static/shop/460px/2012/12/5385-127-sale.jpg”

    I want to parse this JSON according to the categories. Can you help me to do that using your tutorial?

  10. Furkan Damar on October 22, 2013 at 1:08 pm

    Eyvallah kardeşim Allah razı olsun

  11. gkl on September 14, 2015 at 1:24 pm

    in json data if we remove a currency it stops what is the issue why app stop pls help me

  12. sartaz on September 19, 2015 at 3:41 pm

    i have to use {“country:”0″,


    how to use in my android programme with json with this service
    plz help me

  13. aneesirshad on January 29, 2016 at 1:14 pm

    how i create search view and show result another activity in list. using json through api in android studio.

  14. Ashutosh on February 13, 2016 at 12:27 pm

    if we have to do JSON Parsing Using Fragment or by extending Fragment classes how should i do it????

  15. rahul on March 30, 2016 at 8:14 pm

    i want the listview under Fragment is main issue

Leave a Reply

Your email address will not be published. Required fields are marked *

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner