Android JSON Parsing with JSONObject and loading to ListView – Example

September 10, 2012
By

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


<resources>

    <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>

</resources>


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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ListView
        android:id="@+id/lv_countries"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:context=".MainActivity" />
</RelativeLayout>


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="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/tv_country"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:textSize="20dp"
        android:textStyle="bold" />

    <ImageView
        android:id="@+id/iv_flag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv_country"
        android:layout_centerVertical="true"
        android:padding="4dp"
        android:contentDescription="@string/str_iv_flag" />

    <TextView
        android:id="@+id/tv_country_details"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/iv_flag"
        android:layout_below="@id/tv_country" />

</RelativeLayout>


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


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) {
            e.printStackTrace();
        }
        /** 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));
                countryList.add(country);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        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) {
            e.printStackTrace();
        }
        return country;
    }
}


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


package in.wptrafficanalyzer.listviewwithjson;

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

import org.json.JSONObject;

import android.app.Activity;
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 {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        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 */
        listViewLoaderTask.execute(strJson);
    }

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

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

            CountryJSONParser countryJsonParser = new CountryJSONParser();

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

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

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

            /** Ids of views in listview_layout */
            int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};

            /** 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 */
        @Override
        protected void onPostExecute(SimpleAdapter adapter) {

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

            /** Setting the adapter containing the country list to listview */
            listView.setAdapter(adapter);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, 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

http://developer.android.com/guide/index.html


How to hire me?

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

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

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

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



Tags: , , , , , , ,

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

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

    great…thanks…

  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

    Thanx

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

      Hi,
      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": [
    "4",
    "33",
    "34",
    "16"
    ],
    “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

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