Android JSON parser

Android JSON parser and populating in a listview




In this tutorial we are going to learn how to create a android json parser and populating the results in a ListView, This is more advance technique to parse json if you are a beginner i recommend you reading JSON parsing in android using PHP and MySqli. Let’s get started For android json parser and populating in a listview



Live Demo

Android JSON parser and populating in a listview

Sample JSON

Following is the sample JSON that we are going to parse in this tutorial. This is very simple JSON which gives us list of contacts where each node contains contact information like id, name, email, numbers JSON Response

The difference between [ and { – (Square brackets and Curly brackets)

In general all the JSON nodes will start with a square bracket or with a curly bracket. The difference between [ and { is, the square bracket [ represents starting of an JSONArray node whereas curly bracket { represents JSONObject. So while accessing these nodes we need to call appropriate method to access the data.

If your JSON node starts with [, then we should use getJSONArray() method. Same as if the node starts with {, then we should use getJSONObject() method.
Android JSON parser

Project Structure

Android JSON parser
Project Structure

AndroidManifest.xml

In this file we will add the Internet permission android.permission.INTERNET So that your app can access the internet for fetching json AndroidManifest Permission

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.hackerkernel.restapi" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".detail"
            android:label="@string/title_activity_detail"
            android:parentActivityName=".MainActivity" >
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.hackerkernel.restapi.MainActivity" />
        </activity>
    </application>

</manifest>

activity_main.xml

In this file we will define the layout of your application. In this case we will have a ProgressBar and ListView, ProgressBar has the id of ProgressBar & ListView has a id of ListView

<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"    
                tools:context=".MainActivity">

    <ProgressBar
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progressBar"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:visibility="invisible"/>

    <ListView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"/>

</RelativeLayout>



MainActivity.java

  1. From line 18 to 20 we are setting some private global variables of ProgressBar,ListView & List
  2. From line 27 to 28 we are getting the refernce of ProgressBar & ListView and saving them in variables which we have created in the first step
  3. On line 54 we will create a inner class name Fetcher Which will Extends AsyncTask
  4. On line 58 we are setting the ProgressBar to visible pb.setVisibility(View.VISIBLE);
  5. On line 63 we are calling the HttpManger.getData() method which we will create in a minute
  6. On line 69 we are calling the ContactAdapter(s);, This Method will adapat the List contactList into a ListView, We will create this method in a minute And we are also Setting the Progressbar to invisible on line 70 pb.setVisibility(View.INVISIBLE);
  7. On line 31 we are creating a instance of Fetcher Inner class and then calling the execute() method and providing the JSON URL as argument
  8. On line 46 we will create ContactAdapter() method which will call the JsonParser.parse()(We Will create in a Minute) and save it in contactList and then adapt the contactList in a listView
  9. on line 34 we are setting the lv.setOnItemClickListener() on the listView, Whenever the user click the listView we will get the text from the listView and store it in a variable name and then we will send this variable to Detail Activity via intent
package com.hackerkernel.restapi;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;

import java.util.List;


public class MainActivity extends ActionBarActivity {

    private ProgressBar pb;
    private ListView lv;
    private List<String> contactList;

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

        pb = (ProgressBar) findViewById(R.id.progressBar);
        lv = (ListView) findViewById(R.id.listView);
        /*fetch data from the web*/
        Fetcher fetcher = new Fetcher();
        fetcher.execute("http://10rsfreerecharge.site11.com/getJsonResponse.php");

        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name = (String) lv.getItemAtPosition(position);
                Intent intent = new Intent(MainActivity.this,detail.class);
                intent.putExtra("name", name);
                startActivity(intent);
            }
        });
    }


    public void ContactAdapter(String json){
        contactList = JsonParser.Parse(json);

        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,contactList);
        lv.setAdapter(adapter);
    }

    //AsyncTask
    private class Fetcher extends AsyncTask<String,String,String>{

        @Override
        protected void onPreExecute() {
            pb.setVisibility(View.VISIBLE);
        }

        @Override
        protected String doInBackground(String... params) {
            String data = HttpManger.getData(params[0]);
            return data;
        }

        @Override
        protected void onPostExecute(String s) {
            ContactAdapter(s);
            pb.setVisibility(View.INVISIBLE);
        }
    }
}

HttpManger.java

This class will fetch the json response from the server, For this stuff we will be using HttpUrlConnection

package com.hackerkernel.restapi;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpManger {

    public static String getData(String stringUrl) {
        BufferedReader reader = null;
        try {
            URL url = new URL(stringUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            StringBuilder sb = new StringBuilder();

            InputStreamReader is = new InputStreamReader(connection.getInputStream());

            reader = new BufferedReader(is);

            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append("\n");
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

JsonParse.java

In JsonParse we have a static method Parse which take json string as an argument and then it format the jsonstring and store the name returned from the json into a List and then return that list.

package com.hackerkernel.restapi;


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

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

public class JsonParser {

public static List Parse(String json){

        try {
            JSONArray jsonArray = new JSONArray(json);
            List contactList = new ArrayList<>();
            
            int i = 0;
            while (i < jsonArray.length()){
                JSONObject jb = jsonArray.getJSONObject(i);

                contactList.add(jb.getString("name"));
                i++;
            }

            return contactList;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
    
}



Detail Activity

In this activity we will show which name of the item which has been clicked by the user

activity_detail.xml

This is the layout file of detail activity. In this layout file we only have a TextView where we will display the name which we have clicked.

<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"
                tools:context="com.hackerkernel.restapi.detail">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"/>

</RelativeLayout>

detail.java

  1. on line 17 we are setting the refernce of the textView in tv variable
  2. on line 20 we are we are getting the name from the intent and storing it in a variable name
  3. on line 22 we are setting the text to tv variable
package com.hackerkernel.restapi;

import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;


public class detail extends ActionBarActivity {

    TextView tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);

        tv = (TextView)findViewById(R.id.textView);

        //store the text in variable
        String name = getIntent().getExtras().getString("name");
        //display text
        tv.setText(name);
    }

}



11 thoughts on “Android JSON parser and populating in a listview

  1. thanks a lot, but i’ve got error like this
    1714-1760/? E/InputDispatcher﹕ Motion event has invalid pointer count 0; value must be between 1 and 16.

    what should i do??

  2. {
    “contacts”: [
    {
    “id”: “c200”,
    “name”: “Ravi Tamada”,
    “email”: “ravi@gmail.com”,
    “address”: “xx-xx-xxxx,x – street, x – country”,
    “gender” : “male”,
    “phone”: {
    “mobile”: “+91 0000000000”,
    “home”: “00 000000”,
    “office”: “00 000000”
    }
    },
    {
    “id”: “c201”,
    “name”: “Johnny Depp”,
    “email”: “johnny_depp@gmail.com”,
    “address”: “xx-xx-xxxx,x – street, x – country”,
    “gender” : “male”,
    “phone”: {
    “mobile”: “+91 0000000000”,
    “home”: “00 000000”,
    “office”: “00 000000”
    }
    },
    }
    ]
    }

    How to parse thisd kind of json string where there is no array name?
    where i have to change?

    1. JSONObject jo = new JSONObject(jsonString);
      JSONArray array = jo.getJSONArray(“contacts”);
      for (int i = 0; i < array.length(); i++) { //now get jsonObject JSONObject obj = array.getJSONObject(i); //get data String id = obj.getString("id"); } This code will help you

  3. Hello,
    Nice tutorial. It really helped me with my project work. However, I have a small query:
    I needed to add an additional line in a row in the listview.
    My json data is the following:
    [{
    “product”:”JACKET MENS XL \u0026 SMALL HENRI LLOYD, WOMENS SIZE 8 GILL SAILING TYPE”,
    “url”:”http://sfbay.craigslist.org/eby/clo/5393894754.html”},{
    “product”:”Car Alarm”,
    “url”:”http://sfbay.craigslist.org/eby/eld/5393862160.html”},{
    “product”:”NOBODY CAN BEAT BIG RAY December DEAL 2001″,
    “url”:”http://sfbay.craigslist.org/sby/mcd/5370463657.html”
    }]

    I want to display both the product and the url in a single row (in the listview) in the main activity and display the same in the next activity. I tried a lot of modifications, but the last mod gives me separate rows for product and url.
    Kindly post a code which will help me in achieving the desired result and where to place the code in the individual files.

    Thanks

    1. To achieve that you need to create a custom ListView and Adapter which can display two item. I will be doing a tutorial on that soon.

  4. How to display the remaining Json objects (email, id, number) in the detail activity?

    i mean where to pass the intent? please help

    1. Inside onItemClickListener Create a intenet and putExtra in the intent For Ex:
      listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView< ?> parent, View view,int position, long id) {
      Intent myIntenet = new Intent();
      myintent.putExtra(“email”,data);
      startActivity(myintent);
      }
      });

      1. Hi,

        i tried passing other jason objects (email, name, id , number) in onitemclicklistener..its not taking though..i also updated the detail activity file

        If i click on name: i should get other details displayed in the detail activity…but everytime its giving just the name of the person..dont know why..

        please help

Leave a Reply

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