This tutorial demonstrates how to do Android JSON Parsing and display with RecyclerView or ListView. The data may be from JSON file or PHP.

To fetch JSON data in android i used java’s builtin class called AsyncTask and HttpUrlConnection and Android JSON Parsing will be done by using JSONArray and JSONObject class and finally, to display data i used RecyclerView(Supported in android suport library v7). Let’s get started.

Download Code From Github

Android JSON Parsing Demo

JSON

The below is an example of fish data i’m using which has some basic info like image url, fish name, category, size and price.

example.json

[{"fish_img":"1.jpg","fish_name":"Indian Mackerel","cat_name":"Marine Fish","size_name":"Medium","price":"100"},
{"fish_img":"2.jpg","fish_name":"Manthal Repti","cat_name":"Marine Fish","size_name":"Small","price":"200"},
{"fish_img":"3.jpg","fish_name":"Baby Sole Fish","cat_name":"Marine Fish","size_name":"Small","price":"600"},
{"fish_img":"4.jpg","fish_name":"Silver Pomfret","cat_name":"Marine Fish","size_name":"Large","price":"300"},
{"fish_img":"5.jpg","fish_name":"Squid","cat_name":"Shell Fish","size_name":"Small","price":"800"},
{"fish_img":"6.jpg","fish_name":"Clam Meat","cat_name":"Shell Fish","size_name":"Small","price":"350"},
{"fish_img":"7.jpg","fish_name":"Indian Prawns","cat_name":"Shell Fish","size_name":"Medium","price":"270"},
{"fish_img":"8.jpg","fish_name":"Mud Crab","cat_name":"Shell Fish","size_name":"Medium","price":"490"},
{"fish_img":"9.jpg","fish_name":"Grey Mullet","cat_name":"Backwater Fish","size_name":"Small","price":"670"},
{"fish_img":"10.jpg","fish_name":"Baasa","cat_name":"Backwater Fish","size_name":"Large","price":"230"},
{"fish_img":"11.jpg","fish_name":"Pearl Spot","cat_name":"Backwater Fish","size_name":"Small","price":"340"},
{"fish_img":"12.jpg","fish_name":"Anchovy","cat_name":"Marine Fish","size_name":"Small","price":"130"},
{"fish_img":"13.jpg","fish_name":"Sole Fish","cat_name":"Marine Fish","size_name":"Medium","price":"250"},
{"fish_img":"14.jpg","fish_name":"Silver Croaker","cat_name":"Marine Fish","size_name":"Small","price":"220"}]

Android

The files and steps used in this tutorial as follow.

Adding Dependencies

Open your build.gradle(Module: app) file and add the following dependencies highlighted below and sync your project gradle.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:recyclerview-v7:23.3.0'
    compile 'com.github.bumptech.glide:glide:3.5.2'
}

Note: You may need to replace the version of dependency files added except glide dependency, in my case version is 23.3.0. You can find your build tool version on top of same page.

MainActivity.java: Fetch JSON and Android JSON Parsing

The step by step procedure as follow

  1. Immediate after creation of activity an call to AsyncFetch class is made to carry out Asynchronous task.
  2. onPreExecute(), invoked on the UI thread before the task is executed. Here We are displaying loading message.
  3. doInBackground(Params…), invoked on the background thread immediately after
    onPreExecute() finishes executing. The recieving of data from JSON file using HttpURLConnection class has done in this function.
  4. onPostExecute(Result), invoked on the UI thread after the background computation finishes. Here we are extracting data recieved from JSON file and Android JSON Parsing will be done.
  5. Finally, the data is passed to adapter to display it on RecyclerView.
package com.androidcss.jsonexample;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    private RecyclerView mRVFishPrice;
    private AdapterFish mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Make call to AsyncTask
        new AsyncFetch().execute();
    }

    private class AsyncFetch extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
        HttpURLConnection conn;
        URL url = null;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();

        }

        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL("http://192.168.1.7/test/example.json");

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;

                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }


        }

        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            pdLoading.dismiss();
            List<DataFish> data=new ArrayList<>();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataFish fishData = new DataFish();
                    fishData.fishImage= json_data.getString("fish_img");
                    fishData.fishName= json_data.getString("fish_name");
                    fishData.catName= json_data.getString("cat_name");
                    fishData.sizeName= json_data.getString("size_name");
                    fishData.price= json_data.getInt("price");
                    data.add(fishData);
                }

                // Setup and Handover data to recyclerview
                mRVFishPrice = (RecyclerView)findViewById(R.id.fishPriceList);
                mAdapter = new AdapterFish(MainActivity.this, data);
                mRVFishPrice.setAdapter(mAdapter);
                mRVFishPrice.setLayoutManager(new LinearLayoutManager(MainActivity.this));

            } catch (JSONException e) {
                Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}

DataFish.java

package com.androidcss.jsonexample;

public class DataFish {

    public String fishImage;
    public String fishName;
    public String catName;
    public String sizeName;
    public int price;
}

AdapterFish.java

Here Binding data to views and recycling of views will be done when user scroll through RecyclerView.

package com.androidcss.jsonexample;

import android.content.Context;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.Collections;
import java.util.List;

public class AdapterFish extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private Context context;
    private LayoutInflater inflater;
    List<DataFish> data= Collections.emptyList();
    DataFish current;
    int currentPos=0;

    // create constructor to innitilize context and data sent from MainActivity
    public AdapterFish(Context context, List<DataFish> data){
        this.context=context;
        inflater= LayoutInflater.from(context);
        this.data=data;
    }

    // Inflate the layout when viewholder created
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view=inflater.inflate(R.layout.container_fish, parent,false);
        MyHolder holder=new MyHolder(view);
        return holder;
    }

    // Bind data
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

        // Get current position of item in recyclerview to bind data and assign values from list
        MyHolder myHolder= (MyHolder) holder;
        DataFish current=data.get(position);
        myHolder.textFishName.setText(current.fishName);
        myHolder.textSize.setText("Size: " + current.sizeName);
        myHolder.textType.setText("Category: " + current.catName);
        myHolder.textPrice.setText("Rs. " + current.price + "\\Kg");
        myHolder.textPrice.setTextColor(ContextCompat.getColor(context, R.color.colorAccent));

        // load image into imageview using glide
        Glide.with(context).load("http://192.168.1.7/test/images/" + current.fishImage)
                .placeholder(R.drawable.ic_img_error)
                .error(R.drawable.ic_img_error)
                .into(myHolder.ivFish);

    }

    // return total item from List
    @Override
    public int getItemCount() {
        return data.size();
    }


    class MyHolder extends RecyclerView.ViewHolder{

        TextView textFishName;
        ImageView ivFish;
        TextView textSize;
        TextView textType;
        TextView textPrice;

        // create constructor to get widget reference
        public MyHolder(View itemView) {
            super(itemView);
            textFishName= (TextView) itemView.findViewById(R.id.textFishName);
            ivFish= (ImageView) itemView.findViewById(R.id.ivFish);
            textSize = (TextView) itemView.findViewById(R.id.textSize);
            textType = (TextView) itemView.findViewById(R.id.textType);
            textPrice = (TextView) itemView.findViewById(R.id.textPrice);
        }

    }

}

activity_main.xml

The xml file for MainActivity.java

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <android.support.v7.widget.RecyclerView
        android:id="@+id/fishPriceList"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingTop="10dp"
        android:layout_weight="1"
        />
</LinearLayout>

container_fish.xml

The xml file for AdapterFish.java

<?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="wrap_content"
    android:clickable="true"
    android:orientation="horizontal"
    android:padding="10dp">

    <ImageView
        android:layout_width="60dp"
        android:scaleType="fitXY"
        android:layout_height="40dp"
        android:id="@+id/ivFish"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="fish name"
        android:id="@+id/textFishName"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/ivFish"
        android:layout_toLeftOf="@+id/textPrice"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="price"
        android:id="@+id/textPrice"
        android:textColor="@color/colorAccent"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="Small Text"
        android:id="@+id/textSize"
        android:layout_marginLeft="5dp"
        android:layout_below="@id/textFishName"
        android:layout_toRightOf="@id/ivFish"
        android:layout_toEndOf="@id/ivFish"
        android:textColor="#666"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:text="sd"
        android:id="@+id/textType"
        android:layout_marginLeft="5dp"
        android:layout_below="@id/textSize"
        android:layout_toRightOf="@id/ivFish"
        android:textColor="#666"/>

</RelativeLayout>

AndroidManifest.xml

Don’t forget to add uses-permission for internet to your AndroidManifest.xml file, otherwise it will give access denied error.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidcss.jsonexample" >
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>