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);
    }

}