Android JSON Parsing And Display With RecyclerView Image And Text

android json parsing using volley, android parse json and show in listview, android json parsing and display with recyclerview, Android JSON Parsing Using Volley And Display With RecyclerView, android upload image using volley, android listview using volley

Android JSON Parsing And Display With RecyclerView example is the current reading content.

You will Learn about Android recyclerview tutorial – fetching json from server in this example.

After JSON parsing, we will populate the recyclerview with image and text.

JSON data will contain string information like country, name, city and image URL.

JSONAarray and JSONObject are the key component of the JSON data structure which we will parse today.

After parsing this data we will show them in recyclerview along with cardview.

We need to use web service to parse JSON from URL or remote Web Service.

Web service enable us to fetch data and to set them in android device.

Final OutCome

Step 1. Gradle File Updation

In this step, we will update the build.gradle(Module:app) file.

To use recyclerview and cardview, we need to fetch some classes from remote server.

Also, we need to have classes for Picasso library which we use to load the image from the URL.

So write the following lines in build.gradle(Module:app) file.

 implementation 'com.squareup.picasso:picasso:2.71828'
 implementation 'com.android.support:recyclerview-v7:27.1.1'
 implementation 'com.android.support:cardview-v7:27.1.1'
  • First line is for Picasso and other two are for recyclerview and cardview.

Step 2. Internet Permission In Manifest

Of course our android app need to use internet for retrieving JSON data from remote server.

So in the AndroidManifest.xml file, add the below line

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

Step 3. HttpRequest Class

To get the remote data, we need to make http call via web service.

For making http calls, there is a class named HttpURLConnection , which helps to make connection to the internet.

Create a new class and give it a name HttpRequest.java 

Write down the following coding lines in HttpRequest.java 

/**
 * Created by Parsania Hardik on 18-Apr-17.
 */

import android.util.Log;

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

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * Since HttpClient,BasicNameValuePairs, etc...  are deprecated.
 * I've searched for a good alternative, and couldn't find any. Eventually ended up writing my own solution, so I decided to share to those who needs it.
 * Main goals: to make it intuitive, short, clean and reasonable.
 * NOTE methods: .prepare(), preparePost(), withData(map) & withData(string) are build to allow caller to chain in different variations, examples:
 *HttpRequest req=new HttpRequest("http://host:port/path");
 *
 *Example 1: //prepare Http Post request and send to "http://host:port/path" with data params name=Bubu and age=29, return true - if worked
 *req.preparePost().withData("name=Bubu&age=29").send();
 *
 *Example 2: //prepare http get request,  send to "http://host:port/path" and read server's response as String
 *req.prepare().sendAndReadString();
 *
 *Example 3: //prepare Http Post request and send to "http://host:port/path" with name=Bubu and age=29 and read server's response as JSONObject
 *HashMap<String, String>params=new HashMap<>();
 params.put("name", "Groot");
 params.put("age", "29");
 *req.preparePost().withData(params).sendAndReadJSON();
 */
public class HttpRequest {
    //Supported HttpRequest methods
    public static enum Method{
        POST,PUT,DELETE,GET;
    }
    private URL url;
    private HttpURLConnection con;
    private OutputStream os;
    //After instantiation, when opening connection - IOException can occur
    public HttpRequest(URL url)throws IOException{
        this.url=url;
        con = (HttpURLConnection)this.url.openConnection();
    }
    //Can be instantiated with String representation of url, force caller to check for IOException which can be thrown
    public HttpRequest(String url)throws IOException{ this(new URL(url)); Log.d("parameters", url); }

    /**
     * Sending connection and opening an output stream to server by pre-defined instance variable url
     *
     * @param //isPost boolean - indicates whether this request should be sent in POST method
     * @throws IOException - should be checked by caller
     * */
    private void prepareAll(Method method)throws IOException{
        con.setDoInput(true);
        con.setRequestMethod(method.name());
        if(method== Method.POST||method== Method.PUT){
            con.setDoOutput(true);
            os = con.getOutputStream();
        }
    }
    //prepare request in GET method
    //@return HttpRequest this instance -> for chaining method @see line 22
    public HttpRequest prepare() throws IOException{
        prepareAll(Method.GET);
        return this;
    }
    /**
     * Prepares HttpRequest method with for given method, possible values: HttpRequest.Method.POST,
     * HttpRequest.Method.PUT, HttpRequest.Method.GET & HttpRequest.Method.DELETE
     *
     * @param method HttpRequest.Method - nested enum HttpRequest.Method constant
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest prepare(Method method)throws IOException{
        prepareAll(method);
        return this;
    }
    /**
     * Adding request headers (standard format "Key":"Value")
     *
     * @param headers String variadic params in standard format "Key":"Value"
     * @return HttpRequest this instance -> for chaining method @see line 22
     * */
    public HttpRequest withHeaders(String... headers){
        for(int i=0,last=headers.length;i<last;i++) {
            String[]h=headers[i].split("[:]");
            con.setRequestProperty(h[0],h[1]);
        }
        return this;
    }

    /**
     * Writes query to open stream to server
     *
     * @param query String params in format of key1=v1&key2=v2 to open stream to server
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(String query) throws IOException{
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
        writer.write(query);
        writer.close();
        return this;
    }
    /**
     * Builds query on format of key1=v1&key2=v2 from given hashMap structure
     * for map: {name=Bubu, age=29} -> builds "name=Bubu&age=29"
     * for map: {Iam=Groot} -> builds "Iam=Groot"
     *
     * @param params HashMap consists of key-> value pairs to build query from
     * @return HttpRequest this instance -> for chaining method @see line 22
     * @throws IOException - should be checked by caller
     * */
    public HttpRequest withData(HashMap<String,String> params) throws IOException{
        StringBuilder result=new StringBuilder();
        for(Map.Entry<String,String>entry : params.entrySet()){
            result.append((result.length()>0?"&":"")+entry.getKey()+"="+entry.getValue());//appends: key=value (for first param) OR &key=value(second and more)
            Log.d("parameters",entry.getKey()+"  ===>  "+ entry.getValue());
        }
        withData(result.toString());
         return this;
    }
    //When caller only need to send, and don't need String response from server
    public int send() throws IOException{
        return con.getResponseCode(); //return HTTP status code to indicate whether it successfully sent
    }
    /**
     * Sending request to the server and pass to caller String as it received in response from server
     *
     * @return String printed from server's response
     * @throws IOException - should be checked by caller
     * */
    public String sendAndReadString() throws IOException{
        BufferedReader br=new BufferedReader(new InputStreamReader(con.getInputStream()));
        StringBuilder response=new StringBuilder();
        for(String line;(line=br.readLine())!=null;)response.append(line+"\n");
        Log.d("ressss",response.toString());
        return response.toString();
     }
    /**
     * Sending request to the server and pass to caller its raw contents in bytes as it received from server.
     *
     * @return byte[] from server's response
     * @throws IOException - should be checked by caller
     * */
    public byte[] sendAndReadBytes() throws IOException{
        byte[] buffer = new byte[8192];
        InputStream is = con.getInputStream();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        for (int bytesRead;(bytesRead=is.read(buffer))>=0;)output.write(buffer, 0, bytesRead);
        return output.toByteArray();
    }
    //JSONObject representation of String response from server
    public JSONObject sendAndReadJSON() throws JSONException, IOException{
        return new JSONObject(sendAndReadString());
    }
}
  • Methods of above class enable us to make GET and POST http calls.
  • In GET call, there is no parameter and while POST calls do require parameters along with URL of Web Service.

Step 4. Model Data Class

To maintain the various information among all the children of the recyclerview, we will make one data model class.

This class helps us to simplify the data maintaining task in adapter class.

So prepare a new class named RogerModel.java

Copy the following source code in RogerModel.java class.

public class RogerModel {

    private String name, country, city, imgURL;

    public String getImgURL(){
        return imgURL;
    }

    public void setImgURL(String imgURL){
        this.imgURL = imgURL;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }
}
  • As you can see that we have getter and setter methods for different string like country, name, city and image url.

Step 5. XML file for Recyclerview child

For maintaining the same view across all the children of recyclerview, we need one separate XML layout file.

Make a new XML file under res->layout directory and give it a name rv_item.xml.

Write down the below code block in rv_item.xml.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        app:cardCornerRadius="5dp">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="horizontal">


            <ImageView
                android:id="@+id/iv"
                android:layout_width="100dp"
                android:layout_height="100dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:scaleType="fitXY" />

            <LinearLayout
                android:layout_width="wrap_content"
                android:layout_height="100dp"
                android:layout_marginLeft="10dp"
                android:layout_marginTop="10dp"
                android:orientation="vertical">

                <TextView
                    android:id="@+id/name"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_marginTop="5dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/country"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

                <TextView
                    android:id="@+id/city"
                    android:layout_width="wrap_content"
                    android:layout_height="0dp"
                    android:layout_weight="1"
                    android:text="ddd"
                    android:textColor="#000"
                    android:textStyle="bold" />

            </LinearLayout>
        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
  • As you have seen in above code, main components are ImageView and Three textviews.
  • I have written a code for CardView as a parent of all other components.
  • CardView will create attractive view to make recyclerview looks more beautiful 🙂

Step 6. RogerAdapter class

For setting the data in every row item of recyclerview, we need to make appropriate adapter class.

Create a new class named “RogerAdapter.java” and add the following code

import android.content.Context;
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.squareup.picasso.Picasso;
import java.util.ArrayList;

public class RogerAdapter extends RecyclerView.Adapter<RogerAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<RogerModel> rogerModelArrayList;

    public RogerAdapter(Context ctx, ArrayList<RogerModel> rogerModelArrayList){

        inflater = LayoutInflater.from(ctx);
        this.rogerModelArrayList = rogerModelArrayList;
    }

    @Override
    public RogerAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        View view = inflater.inflate(R.layout.rv_item, parent, false);
        MyViewHolder holder = new MyViewHolder(view);

        return holder;
    }

    @Override
    public void onBindViewHolder(RogerAdapter.MyViewHolder holder, int position) {

        Picasso.get().load(rogerModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.name.setText(rogerModelArrayList.get(position).getName());
        holder.country.setText(rogerModelArrayList.get(position).getCountry());
        holder.city.setText(rogerModelArrayList.get(position).getCity());
    }

    @Override
    public int getItemCount() {
        return rogerModelArrayList.size();
    }

    class MyViewHolder extends RecyclerView.ViewHolder{

        TextView country, name, city;
        ImageView iv;

        public MyViewHolder(View itemView) {
            super(itemView);

            country = (TextView) itemView.findViewById(R.id.country);
            name = (TextView) itemView.findViewById(R.id.name);
            city = (TextView) itemView.findViewById(R.id.city);
            iv = (ImageView) itemView.findViewById(R.id.iv);
        }

    }
}
  • In the constructor of this adapter class, compiler will get an Arraylist (rogerModelArrayList) with the objects of the RogerModel class.
  • onBindViewHolder() method from the above class, set the information in imageview and textviews using rogerModelArrayList.
  • Every object from rogerModelArrayList is used to populate every single row item of recyclerview.

Step 7. At the End

Now we close to the end of this tutorial.

Replace the code of activity_main.xml with the following code block

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#cd15e6"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Below RecyclerView is populated from JSON Data"
        android:textColor="#fff"
        android:textStyle="bold"
        />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_marginTop="15dp"/>


</LinearLayout>
  • I have taken one textview and one recyclerview in the main layout file.

In the MainActivity.java file copy the below source code

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.Context;
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.util.Log;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;

public class MainActivity extends AppCompatActivity {

    private String jsonURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private final int jsoncode = 1;
    private RecyclerView recyclerView;
    ArrayList<RogerModel> rogerModelArrayList;
    private RogerAdapter rogerAdapter;
    private static ProgressDialog mProgressDialog;

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

        recyclerView = findViewById(R.id.recycler);

        fetchJSON();

    }
    @SuppressLint("StaticFieldLeak")
    private void fetchJSON(){

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                HashMap<String, String> map=new HashMap<>();
                try {
                    HttpRequest req = new HttpRequest(jsonURL);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss",result);
                onTaskCompleted(result,jsoncode);
            }
        }.execute();
    }

    public void onTaskCompleted(String response, int serviceCode) {
        Log.d("responsejson", response.toString());
        switch (serviceCode) {
            case jsoncode:

                if (isSuccess(response)) {
                    removeSimpleProgressDialog();  //will remove progress dialog
                    rogerModelArrayList = getInfo(response);
                    rogerAdapter = new RogerAdapter(this,rogerModelArrayList);
                    recyclerView.setAdapter(rogerAdapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

                }else {
                    Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
                }
        }
    }

    public ArrayList<RogerModel> getInfo(String response) {
        ArrayList<RogerModel> tennisModelArrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    RogerModel playersModel = new RogerModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);
                    playersModel.setName(dataobj.getString("name"));
                    playersModel.setCountry(dataobj.getString("country"));
                    playersModel.setCity(dataobj.getString("city"));
                    playersModel.setImgURL(dataobj.getString("imgURL"));
                    tennisModelArrayList.add(playersModel);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return tennisModelArrayList;
    }

    public boolean isSuccess(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.optString("status").equals("true")) {
                return true;
            } else {

                return false;
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return false;
    }

    public String getErrorCode(String response) {

        try {
            JSONObject jsonObject = new JSONObject(response);
            return jsonObject.getString("message");

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "No data";
    }

    public static void removeSimpleProgressDialog() {
        try {
            if (mProgressDialog != null) {
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                    mProgressDialog = null;
                }
            }
        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();

        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public static void showSimpleProgressDialog(Context context, String title,
                                                String msg, boolean isCancelable) {
        try {
            if (mProgressDialog == null) {
                mProgressDialog = ProgressDialog.show(context, title, msg);
                mProgressDialog.setCancelable(isCancelable);
            }

            if (!mProgressDialog.isShowing()) {
                mProgressDialog.show();
            }

        } catch (IllegalArgumentException ie) {
            ie.printStackTrace();
        } catch (RuntimeException re) {
            re.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

Getting Maximum from Above Code

Let us read and understand what above code is doing.

Consider the following code

 private String jsonURL = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private final int jsoncode = 1;
    private RecyclerView recyclerView;
    ArrayList<RogerModel> rogerModelArrayList;
    private RogerAdapter rogerAdapter;
    private static ProgressDialog mProgressDialog;
  • First string variable contains the URL from which we will get the JSON data.
  • Second line have one integer variable which will be used in onTaskComplete method.
  • Third line is simply creating an object for RecyclerView.
  • Fourth line is making an arraylist with objects of the RogerModel class.
  • Fifth one is making one object of RogerAdapter class and last one is making an object of progress dialog.

Look at the below line

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

        recyclerView = findViewById(R.id.recycler);

        fetchJSON();

    }
  • in onCreate() method I am calling a method named fetchJSON()

Code for this method is as the below

  @SuppressLint("StaticFieldLeak")
    private void fetchJSON(){

        showSimpleProgressDialog(this, "Loading...","Fetching Json",false);

        new AsyncTask<Void, Void, String>(){
            protected String doInBackground(Void[] params) {
                String response="";
                HashMap<String, String> map=new HashMap<>();
                try {
                    HttpRequest req = new HttpRequest(jsonURL);
                    response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
                } catch (Exception e) {
                    response=e.getMessage();
                }
                return response;
            }
            protected void onPostExecute(String result) {
                //do something with response
                Log.d("newwwss",result);
                onTaskCompleted(result,jsoncode);
            }
        }.execute();
    }
  • This is the method where compiler will make an http call.
  • Compiler will use AsyncTask class to make an http call with required parameters and URL.
  • When the http call is done successfully, compiler will execute onPostExecute() method.
  • onPostExecute() method will call the onTaskCompleted() method.

JSON response will look like the below

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/roger.jpg"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/nadal.jpg"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/djoko.jpg"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/murray.jpg"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/shara.jpg"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/woz.jpg"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/bou.png"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade",
            "imgURL": "https://demonuts.com/Demonuts/SampleImages/iva.jpg"
        }
    ]
}

onTaskCompleted() method’s code structure is as the following

public void onTaskCompleted(String response, int serviceCode) {
        Log.d("responsejson", response.toString());
        switch (serviceCode) {
            case jsoncode:

                if (isSuccess(response)) {
                    removeSimpleProgressDialog();  //will remove progress dialog
                    rogerModelArrayList = getInfo(response);
                    rogerAdapter = new RogerAdapter(this,rogerModelArrayList);
                    recyclerView.setAdapter(rogerAdapter);
                    recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

                }else {
                    Toast.makeText(MainActivity.this, getErrorCode(response), Toast.LENGTH_SHORT).show();
                }
        }
    }
  • first, compiler will check if the status of JSON response is true or false (see in above JSON response).
  • If the status is true then compiler will go inside the if condition.
  • Then it will get the information from the getInfo() method.

getInfo() method has the below coding lines

public ArrayList<RogerModel> getInfo(String response) {
        ArrayList<RogerModel> tennisModelArrayList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(response);
            if (jsonObject.getString("status").equals("true")) {

                JSONArray dataArray = jsonObject.getJSONArray("data");

                for (int i = 0; i < dataArray.length(); i++) {

                    RogerModel playersModel = new RogerModel();
                    JSONObject dataobj = dataArray.getJSONObject(i);
                    playersModel.setName(dataobj.getString("name"));
                    playersModel.setCountry(dataobj.getString("country"));
                    playersModel.setCity(dataobj.getString("city"));
                    playersModel.setImgURL(dataobj.getString("imgURL"));
                    tennisModelArrayList.add(playersModel);

                }
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return tennisModelArrayList;
    }
  • Compiler will rotate the for loop for the number of iterations equals to the number of objects present in the JSONArray named “data”
  • After getting all the data, compiler will send it to the adapter class and adapter will finally populate the recyclerview.

Download Source Code For Android JSON Parsing And Display With RecyclerView

[sociallocker]Download Source Code For Json_Recyclerview_Old[/sociallocker]