Skip to main content

Android JSON Parsing and display with RecyclerView

Fetch JSON data in Android and display with RecyclerView

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


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.


[{"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"}]


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 ''
    compile ''
    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. 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.os.AsyncTask;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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;

    protected void onCreate(Bundle savedInstanceState) {
        //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;

        protected void onPreExecute() {

            //this method will be running on UI thread


        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("");

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

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();

                // setDoOutput to true as we recieve data from json file

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                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) {

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

                } else {

                    return ("unsuccessful");

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


        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            List<DataFish> data=new ArrayList<>();

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

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

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



package com.androidcss.jsonexample;

public class DataFish {

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

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.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){
        inflater= LayoutInflater.from(context);;

    // Inflate the layout when viewholder created
    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
    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.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("" + current.fishImage)


    // return total item from List
    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) {
            textFishName= (TextView) itemView.findViewById(;
            ivFish= (ImageView) itemView.findViewById(;
            textSize = (TextView) itemView.findViewById(;
            textType = (TextView) itemView.findViewById(;
            textPrice = (TextView) itemView.findViewById(;




The xml file for

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android=""


The xml file for

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


        android:text="fish name"


        android:text="Small Text"




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=""
    package="com.androidcss.jsonexample" >
    <uses-permission android:name="android.permission.INTERNET"/>
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

Gururaj P Kharvi

An Entrepreneur, Web and Android developer from India.

53 thoughts on “Android JSON Parsing and display with RecyclerView

    1. JSON file can be created with extension as .json or even .txt(text file) also works. JSON has its own syntax to follow when deal with content, for example if i put some data inside square brackets then it treated as array. If you have your data and you want to organize that data then you can create json file and feed your data appropriately and give it to system(in my case it’s android) that understands your json data.

      If you understand what XML files are, i think you understand the purpose of JSON too.

      For more information you can refer json tutorial on w3schools

  1. Hi Guru,

    May I know how should I do if I want to fetch the SQL data from xampp server using php and display in the list view like the example above? Really appreciate your help.
    Btw your code were awesome!

    1. To fetch data from php the method is same as above. The small change you have to do is specify .php file in place of .json file.

      note: In PHP you need to encode your data to json data. Use json_encode() function in PHP to encode data. See example below.

                $sql = 'SELECT fish_img,fish_name, cat_name, size, price  FROM tbl_fish';
                $statement = $connection->prepare($sql);
      				$row_all = $statement->fetchall(PDO::FETCH_ASSOC);
      				header('Content-type: application/json');
         		  		echo json_encode($row_all);

      If you don’t know how to test your app with XAMP or WAMP then please follow the below steps.

      1. You need to find the IPV4 address of your computer. If you are using windows system, then you can open command prompt and type ipconfig for ipv4 address.
      2. Make sure XAMP is running, Now open your browser and enter your ipv4 address and go. If you see result same as result when you enter localhost then you can proceed to next step and if some error you see then you may need to map your xamp localhost to your computer ipv4 address. Unfortunately, i don’t know how to do with xamp server but i know how to in wamp server. If you are interested in installing wamp, you can refer How to install and setup PHP and MySql in windows 10 and 7 tutorial and in wamp to map your localhost to ipv4 address, goto menu and click on put online. The following figure depict the same.
        Wamp server put online
      3. In your android code enter address as

        For example

        (please note that which is same as


        and entering address with localhost does not work with android, you should specify ipv4 address only)

      4. Now, run your app in emulator to see result and if you want to run your app on your android mobile then make sure that both of your computer and mobile connected to same wifi router.
  2. Hi, lovely tutorial, simple and clean. Very learning a lot and receiving much help from this. But i was wondering, what if the Async method is actually in a fragment, as i am using a fragment. What can i do to achieve the findViewById, currently i cannot do it. Hope you can reply me 🙂

    1. @Bowie

      Use following lines of code if you are using Async in fragment. Replace the similar code on onPostExecute(String result) method. For your understanding, i marked the changes made in code.

      // Setup and Handover data to recyclerview
      mRVFishPrice = (RecyclerView)getView().findViewById(;
      mAdapter = new AdapterFish(getActivity(), data);
      mRVFishPrice.setLayoutManager(new LinearLayoutManager(getActivity()));
  3. Hi Gururaj,

    I just want to voice my opinion in that this is one of the best online android tutorials on how to fetch/retrieve items from MySQL. It’s really well written, clearly understandable and works out of the box.

    In my project I have about 100 items that I fetch and I want to implement a favourites feature. I already have my favourite button with an onClick ready to go, can you please guide us to add/remove fetched items (text and images) to a “favorites” activity using SharedPreferences please? There doesn’t seem to be any good online examples of this feature.

    Much appreciated, thank you.

      1. Gururaj,

        I learned about sqlite yesterday (thank you for mentioning it) and then modified the adapter class to include the code (onClick) to insert NAME and URL to sqlite. I used Android Studio to extract the sqlite db onto my computer and then browsed the db, I actually see the values stored in the correct db, table and columns.

        ..Now the challenge is to actually view the data inside a new Favorites activity using recycle view and cardview.

          1. Gururaj with your suggestion I was able to get a step further, however I’m facing an issue now. I can read/write to sqlite in my adapter class, however I need to read the db and change the color of a textview depending on the value of the url. If the db url matches the current url value inside card view then the color of a textview should be “blue”. If the current url doesn’t match what is inside the db then the color should be “red”. I know I need to do this operation outside the adapter class and away from onBindViewHolder for performence but not sure how yet.

            UsersAdapter.Java =

            Basically fontFamilyText3.setTextColor(ContextCompat.getColor(context, R.color.dot_dark_screen1)); inside my adapter should be blue if the url matches what is already inside the db, if not it should be blue.

            I’m stumped in programatically making this.

          2. Apart from changing color, the favorite(add and display) functionality works perfect right?

          3. Gururaj,

            You are correct. Apart from changing color, the favorite(add and display) functionality works perfectly.

          4. In your code, I din’t see any retrieve of data from SQLite(only Insert and Delete) and little confusion in understanding. It will be good if you host your project on GitHub with necessary files so that i can run on my machine and get you solution.

  4. Bro is there any way I can get data in a filtered range eg. My table contains values from 1000 to 10000 and I want when user clicks on 1000-2000 button only that data will be shown in recycler view

    1. When user clicks on range button, send those values to PHP(say 1000 and 2000) and apply limit(select * from table1 limit 1000,2000) in your query. For example, PHP code look like this

      $range_from = $_POST['from'];
      $range_to = $_POST['to'];
      $sql = 'select * from table1 limit :range_from,:range_to';
      $stmt = $conn->prepare($sql);
      $stmt->bindParam(':range_from', $range_from, PDO::PARAM_INT);
      $stmt->bindParam(':range_to', $range_to, PDO::PARAM_INT);
      1. Thanks for you reply, I has test this coding and it works. But I want to change the layout when been view. Not use the fish layout, can i know how to change it? At container fish right.

  5. I understand that is great to learn how to do things using only the android apis. But why not use something more modern like retrofit + rxjava or even just retrofit? You could to the exact same thing with a lot less code! When i started using retrofit i decided i would never go back again! 🙂

    1. You need to have multiple for loop like this.

      JSONArray jArray = new JSONArray(result);
      for(int i=0;i<jArray.length();i++)
        JSONObject json_data = jArray.getJSONObject(i);
        JSONArray fishArray = json_data.getJSONArray("fishes");
        for(int j=0;j<fishArray.length();j++)
           JSONObject fish_data = fishArray.getJSONObject(j);
           // Extract data ex: fish_data.getString("fish_name");
  6. Thank the tutorials is great.But why do too much work on the networking call .Why did you use library like Volley to simplify the network since you also used a library (Glide ) to handle images.

    1. That’s right. I possibly use Volley or Retrofit library in upcoming tutorials but some of my tutorials may still contains AsyncTask because they may directly relate to my previous article.

  7. Hi Gururaj..
    can you help me? How to use putExtra with this tutorial…
    example… from MainActivity to DetailFish?
    because i wanna take this tutorial to my project
    im sorry for bad language english 😀 thanks

  8. I’m just getting the following exception when using this way. Any Ideas?

    “org.json.jsonexception value of type java.lang.string cannot be converted to jsonarray”

    1. The value coming from your PHP file is string so it’s giving error, you need to pass JSON array. better test your PHP file in browser or display toast message to see what exactly returning.

    1. pdloading.dismiss(); statement on onPostExecute() is duplicated. May be that causing the problem. Please remove one of them and re run your app.

  9. Thanks Mr.GuruRaj,Your blog save me from the Bottle neck problem, I have a query i.e. How to show the multiple images in each row in recyclerview from the API ?. Do you have any idea please share it, Thanks in advance.
    Here is Json String:
    “post”: {
    “pm_post_id”: “2655”,
    “pm_user_id”: “6022”,
    “pm_type”: “1”,
    “pm_title”: “”,
    “pm_description”: “Mobile Testing post”,
    “pm_likes”: “1”,
    “pm_comments”: “1”,
    “pm_contributors”: “0”,
    “pm_report”: “0”,
    “pm_views”: “0”,
    “pm_created_on”: “2016-07-27 17:21:43”,
    “pm_updated_on”: “0000-00-00 00:00:00”,
    “pm_shared_type”: “1”,
    “pm_shared_with”: “0”,
    “pm_tags”: “0,126,0”,
    “pm_timeline”: “1”,
    “pm_step”: “0”,
    “pm_status”: “1”,
    “pm_epid”: “0”
    “images_count”: 5,
    “images”: [
    “pg_gallery_id”: “2975”,
    “pg_name”: “iphone.jpeg”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2976”,
    “pg_name”: “iphone5se (1).jpg”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2977”,
    “pg_name”: “profile_blue.png”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2978”,
    “pg_name”: “profile_logo (1).png”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “pg_gallery_id”: “2979”,
    “pg_name”: “elnb.gif”,
    “pg_link”: “”,
    “pg_type”: “1”,
    “pg_date”: “2016-07-27 17:21:43”
    “post_user”: [
    “first_name”: “Michelle”,
    “last_name”: “Smith”,
    “profile_pic”: “tomisima_src1.jpg”

      1. Hi, Awesome tutorial. I want to set image for each cardview. Please, Guru Give answer to if “image count for each row is same”. “I noticed the ‘for Loop’ where the data were declared” Thanks in advance

  10. THis is my Main Activity , the app is crashing the error is

    FATAL EXCEPTION: AsyncTask #1
    Process: com.example.task, PID: 14461
    java.lang.RuntimeException: An error occurred while executing doInBackground()

    What am i doing wrong ???

    // Code stripped out

  11. Thank you very nice tutorial it works for me.
    I tried to put the same code in a fragment class but it doesn’t work and the error message is (E/RecyclerView: No adapter attached; skipping layout) what should i change?
    Thank you.

  12. Hi, This is the best tutorial ever. It will be more awesome if you do a tutorial on using firebase database instead of the usual http call.

    Again, Wonderful tutorial

  13. This is the best working example I’ve tried. minimal coding!!!
    by the way Gururaj P Kharvi do you have any example for Sorting json values by the use of Spinner? Thanks

  14. Hello, We are trying your code, it’s helpful but we got an error “of type JsonObject cannot be converted in JsonArray” and we cannot be able to see our RecyclerView.

    1. The JSON data you are passing is of type object but you need to pass JsonArray because we written the code to parse JsonArray not object.

  15. Thank you for the explanations! A question – what is better, to read my JSON file from a server, or to have it in the raw folder, res directory? If the second case, do I need AsynTask?


      1. Hi,
        please help me with this
        Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview.
        As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment.
        I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it.
        And I have already asked this earlier.
        Please help.

  16. Hi,
    Actually I am receiving an JSON from server and I need to send that data from one fragment to another fragment and show it an recyclerview.
    As you have shown I have stored it an Arraylist but don’t know how to send it to another fragment.
    I have been suggested that I have to store that Arraylist in model then send, but I don’t know how to do it.
    Please help.

  17. Haii Gururaj, i have a simple question for you, but its so difficult for me. The question is, how i can change the color of textview if (sample) the size name is middle then the color is red, or when the size name is small then the color of textview is green. Can you help me?

Leave a Reply

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