Android JSON Parsing Using Volley From URL Example Tutorial

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

Welcome to Android JSON Parsing Using Volley From URL Example Tutorial.

We will learn how to parse JSON from URL or Server Using Volley Library.

You will learn how to fetch/retrieve data from MySQL database in android using json, volley and PHP.

When we want to interact with the remote server, we need to send and fetch data over internet.

For example, when making registration and login module, we need to send username and password to remote server when user completes sign up task.

When user wants to login again, we need to fetch those username and password from the remote server.

In this process of sending and fetching data, we have to make some bridge between android device and remote server.

This tutorial uses Volley as a bridge.

Volley will return our json text in the string format.

Final Looks of JSON Volley

Information About Volley

Volley is a networking library developed by google.

It is an HTTP library that makes networking for android apps easier and faster.

We can also use AsyncTask class for networking purpose which is in-built class for android system.

Main drawback of using AsynTask is it’s inaccuracy. Also little time consuming problem is there for this class.

Steps To Make Example

Follow all the below steps to make a sample project in android studio.

We will fetch JSON data using volley and parse this data using JSONArray and JSONObject class.

Step 1. Dependency part

All the classes of the Volley library are not included in the core android structure.

They are available on GitHub but not in local android library.

So we need to fetch the volley classes in our project using dependency concept.

Add the below line in build.gradle(Module:app) file

implementation 'com.android.volley:volley:1.1.1'

Above line will enable us to use volley library in our project.

Step 2. Model For Players

Now let us create a model class. This class mainly includes getter and setter methods for the various data types.

For example, we have id, name, county and city of the players.

So we will have separate getter and setter methods for all four data types.

Make a new JAVA class named PlayerModel.java 

Copy the below code in PlayerModel.java

public class PlayerModel {

    private String name, country, city, id;

    public String getid() {
        return id;
    }

    public void setid(String id) {
        this.id = id;
    }

    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 required methods for all four data types in above class.

We will use getter methods to fetch the data from the JSON response.

Setter methods will help us to set the data in appropriate UI widget.

Step 3. Main Files

Ok, now last thing is to change activity_main.xml and MainActivity.java files.

Write down below code structure in activity_main.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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text=" below infor is fetched from URL With volley"/>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv"
        android:layout_marginLeft="10dp"
        android:paddingTop="10dp"
        android:paddingBottom="10dp"
        android:textSize="20sp"
        android:textColor="#000"
        android:text=""/>

</LinearLayout>

I have defined two textviews in this file.

First one is just saying that compiler have fetched the below data from URL.

Second one will hold all the data from json response.

Now add the following coding lines into MainActivity.java file

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private TextView textView;

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

        textView = findViewById(R.id.tv);

        requestJSON();

    }

    private void requestJSON(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("strrrrr",">>"+response);

                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

                                ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>();
                                JSONArray dataArray  = obj.getJSONArray("data");

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

                                    PlayerModel playerModel = new PlayerModel();
                                    JSONObject dataobj = dataArray.getJSONObject(i);

                                    playerModel.setid(dataobj.getString("id"));
                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));

                                    playersModelArrayList.add(playerModel);

                                }

                                for (int j = 0; j < playersModelArrayList.size(); j++){
                                    textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName()
                                            + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n");
                                }

                            }else {
                                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        //creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //adding the string request to request queue
        requestQueue.add(stringRequest);

    }

}

Understandings Of Main Logic

Main logic and code is written in the Main Activity.

First of all, read the below lines

 private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
 private TextView textView;

First line is declaring one string variable named “URLstring” . This string includes the URL from which we will fetch JSON response.

Second one is making an object of the textview where we will set the data.

requestJSON() method

in onCreate() method, I have written a requestJSON() method, which will parse the json.

Following is the coding layout for requestJSON() method

 private void requestJSON(){

        StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

                        Log.d("strrrrr",">>"+response);

                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

                                ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>();
                                JSONArray dataArray  = obj.getJSONArray("data");

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

                                    PlayerModel playerModel = new PlayerModel();
                                    JSONObject dataobj = dataArray.getJSONObject(i);

                                    playerModel.setid(dataobj.getString("id"));
                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));

                                    playersModelArrayList.add(playerModel);

                                }

                                for (int j = 0; j < playersModelArrayList.size(); j++){
                                    textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName()
                                            + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n");
                                }

                            }else {
                                Toast.makeText(MainActivity.this, obj.optString("message")+"", Toast.LENGTH_SHORT).show();
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        //displaying the error in toast if occurrs
                        Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

        //creating a request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);

        //adding the string request to request queue
        requestQueue.add(stringRequest);

    }

Consider the below code

 StringRequest stringRequest = new StringRequest(Request.Method.GET, URLstring,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {

Compiler will create an object of the StringRequest class.

First parameter will decide whether volley will execute GET request or POST request. Our URL do not need any URL parameter so we will execute GET request.

Second parameter includes the string variable. This string variable represents the URL which will give us JSON response.

When the volley get any response from the URL, compiler will run onResponse() method.

We will receive our response via the parameter of onResponse() method.

Look at the below few starting lines of onResponse() method.

 try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

                                ArrayList<PlayerModel> playersModelArrayList = new ArrayList<>();
                                JSONArray dataArray  = obj.getJSONArray("data");

Compiler will implement try statement so that if any execution is there, we can avoid force close (app crashing) of our app.

JSON response is looking like below

{
    "status": "true",
    "message": "Data fetched successfully!",
    "data": [
        {
            "id": "1",
            "name": "Roger Federer",
            "country": "Switzerland",
            "city": "Basel"
        },
        {
            "id": "2",
            "name": "Rafael Nadal",
            "country": "Spain",
            "city": "Madrid"
        },
        {
            "id": "3",
            "name": "Novak Djokovic",
            "country": "Serbia",
            "city": "Monaco"
        },
        {
            "id": "4",
            "name": "Andy Murray",
            "country": "United Kingdom",
            "city": "London"
        },
        {
            "id": "5",
            "name": "Maria Sharapova",
            "country": "Russia",
            "city": "Moscow"
        },
        {
            "id": "6",
            "name": "Caroline Wozniacki",
            "country": "Denmark",
            "city": "Odense"
        },
        {
            "id": "7",
            "name": "Eugenie Bouchard",
            "country": "Canada",
            "city": " Montreal"
        },
        {
            "id": "8",
            "name": "Ana Ivanovic",
            "country": "Serbia",
            "city": "Belgrade"
        }
    ]
}

Under try statement, compiler will first get the JSON Object.

then it will check the status.

If the status is true, then it will create an Arraylist with the objects of the PlayerModel class.

Then it will create a JSONArray named “data”. You can see the JSON array named “data” in above JSON response.

Now consider following code snippet

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

                                    PlayerModel playerModel = new PlayerModel();
                                    JSONObject dataobj = dataArray.getJSONObject(i);

                                    playerModel.setid(dataobj.getString("id"));
                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));

                                    playersModelArrayList.add(playerModel);

                                }

Compiler will execute one for loop.

Here, it will create an object of PlayerModel class and an object of JSONObject class.

The it will get the id, name, country and city of the players and will set them using setter methods.

After this, compiler will add the object to the arraylist.

After populating the arraylist with the data of the JSON response, compiler will execute below loop

 for (int j = 0; j < playersModelArrayList.size(); j++){
                                    textView.setText(textView.getText()+ playersModelArrayList.get(j).getid()+ " "+ playersModelArrayList.get(j).getName()
                                            + " "+ playersModelArrayList.get(j).getCountry()+ " "+playersModelArrayList.get(j).getCity()+" \n");
                                }

We will write text in the textview using the above loop. It will write all the information about each player during every iteration of the loop.

Download Source Code For Android JSON Parsing Using Volley

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