Android Volley Tutorial | Get,Post Request With Listview,Recyclerview

android get address from latitude and longitude, android get current address, android get latitude and longitude from address, android volley post request with parameters, android volley get request with parameters, android login and register using volley

Today’s article is about Android Volley Tutorial with examples.

Below is the list of the practical examples on how to use volley in android.

1. Android Volley GET Request With Parameters

2. Android Volley POST Request With Parameters

3. Android JSON Parsing Using Volley And Display With RecyclerView

4. Android ListView Using Volley | Parse JSON Listview

1. Android Volley GET Request With Parameters

Generally, Developers use GET request when there are no parameters in the URL but still you can use GET request with parameters using volley.

For making http GET request using Volley, we need to write parameters and also it’s values in the URL itself.

For example, something like below line

https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username=hardik&password=hardik

Watch GET request

Load the below video to see volley GET request with parameters.

Step 1. Permissions and gradle files

First of all, create a brand new project in android studio.

In this process, select “Empty Activity” as a default template.

Now we need to define INTERNET permission to use the internet of the android device.

Add the below line in AndroidManifest.xml file.

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

To use the volley library in this project, add the following line in build.gradle(Module: app) file.

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

Above line fetch all the classes from volley library so that we can import them easily in our android studio project.

Step 2. Making Second Activity

Create a new activity and give it a name “Second Activity.”

In your activity_second.xml file, add the following code lines

<?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:background="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvusername"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:text="hello"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvpassword"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"/>


</LinearLayout>

Above XML file includes two text views.

One text view will hold the value of first name and second one will get the value of hobby.

Now in SecondActivity.java file, write down the following code snippet

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class SecondActivity extends AppCompatActivity {

    private TextView tvName, tvPass;

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

        tvName = findViewById(R.id.tvusername);
        tvPass = findViewById(R.id.tvpassword);

        tvName.setText(MainActivity.publicFirstName);
        tvPass.setText(MainActivity.publicHobby);

    }
}

Here, we are also taking two text views.

I have set the text value of both the text views using two public variables which we will write in the Main Activity.

Because these string variables (publicFirstName and publicHobby)  are public, we can use them in class of our project using MainActivity. keyword.

Step 3. Default Activity Tasks

When you created new project in android studio, system should have generated two files automatically.

One is activity_main.xml and MainActiivity.java

Now in activity_main.xml file, write down the below coding structure

<?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:background="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="45sp"
        android:text="DemoNuts"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>

</LinearLayout>

Several UI widgets are there in the above file. One text view, two edit texts and one button.

Text view is just saying the name of the company or app.

Among two edit texts, one will get the value of user name and other will get the password from the user.

When the user clicks the button, system will make the https call.

Now in the MainActivity.java file, add the below coding snippet.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;

public class MainActivity extends AppCompatActivity {

    private String URLline = "";

    private EditText etUname, etPass;
    private Button btn;
    public static String publicFirstName, publicHobby;

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

        etUname = findViewById(R.id.etusername);
        etPass = findViewById(R.id.etpassword);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVolley();
            }
        });

    }

    private void getVolley(){

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;

        Log.d("getxxx",URLline);

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

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

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

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

        requestQueue.add(stringRequest);
    }

    public void parseData(String response) {

        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++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    publicFirstName = dataobj.getString("name");
                    publicHobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }
}

Main Activity Writings

Main activity java files has the important code lines to understand.

So consider the below code first,

  private String URLline = "";
  private EditText etUname, etPass;
  private Button btn;
  public static String publicFirstName, publicHobby;

First line making an empty string variable. We will insert the whole URL in this variable later.

Second line is creating an objects of edit text classes. Third line will give the button object.

Fourth line is creating two public static string variables. We can use these public variables anywhere in our whole project. We have used these variables in SecondActivity.java class.

Inside onCreate() method, compiler will first attach the IDs to various Widgets.

Then it will set the onClick() method for the button.

Code for button click event is as the following

 btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getVolley();
            }
        });

Compiler will execute the getVolley() method, when the user clicks the button.

 private void getVolley(){

        final String username = etUname.getText().toString().trim();
        final String password = etPass.getText().toString().trim();

        URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;

        Log.d("getxxx",URLline);

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

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

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

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

        requestQueue.add(stringRequest);
    }

First of all, Compiler will define the two final string variables (username and password).

Edit text etUname will give it’s value in string format to username.

password will get it’s text from etPass edit text.

Now a string variable URLline will get the full URL as per the below line

URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username="+username+"&password="+password;

As you can see that we have attach the parameters at the end of php file using ? sign.

We can separate two parameters using & sign.

Possible URL structure can be like the below line

https://demonuts.com/Demonuts/JsonTest/Tennis/loginGETrequest.php?username=rafa&password=rafa

Now after this coding, compiler will create the object of StringRequest class.

Look at the following code line

 StringRequest stringRequest = new StringRequest(Request.Method.GET, URLline,

Here, first parameter is saying that the type of http request is GET and second parameter is getting the URL structure in string format.

After this much execution, compiler have make GET request to the remote server.

When the server gives JSON response, compiler calls the onResposne() method.

Inside onResposne() method, there is a method named parseData().

parseData() will take the JSON response in string format as it’s parameter.

Following is the code structure for parseData()  method.

public void parseData(String response) {

        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++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    publicFirstName = dataobj.getString("name");
                    publicHobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,SecondActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

Compiler will first parse the json object from the response.

Then it will check the key “status“. If it’s value id “true” then it will create one json array.

This json array is parse using the “data” field.

After this, compiler will create one for loop. Inside this for loop, compiler will give the value to public string variables. (publicFirstName and publicHobby.)

After this, compiler will open second activity.





2. Android Volley POST Request With Parameters

I will write about Android Volley Post Request With Parameters Example today.

You will learn to make volley post request with parameters in android studio.

If we do not need to pass parameters in volley request then we generally use GET request. It will simply make http call without any parameter and will give us JSON response.

See the Parameters

The following video demonstrates the working of this android volley post request example.

Step 1. Permission and Dependency

Make a new project in android studio and set the default activity as the “Empty activity.”

When we want to make http calls to remote server, we need to use internet of android device.

For this, we have to define INTERNET permission in our project.

Add the below line in AndroidManifest.xml file.

<uses-permission android:name="android.permission.INTERNET" />
  • INTERNET permission is not harmful to user privacy so we do not need to ask for runtime permission in this example.

Now in your build.gradle(Module: app) file, add the below line

  implementation 'com.android.volley:volley:1.1.1'
  • Above line will enable us to use some classes of volley library and we can import them in our project.

Step 2. Making Hobby Activity

Create a new activity and give it a name “HobbyActivity.”

System will create two files : activity_hobby.xml and HobbyActivity.java

In the  activity_hobby.xml file, write down the following code lines

<?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:background="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvusername"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:text="hello"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <TextView
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tvpassword"
        android:gravity="center_vertical"
        android:textSize="25sp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"/>


</LinearLayout>

There are two text views are there.

When we call the web service, remote server will send us some data in JSON format. Among these data, we will parse first name and hobby.

Above two text views will hold first name and hobby data.

Now in the HobbyActivity.java, add the below code structure

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class HobbyActivity extends AppCompatActivity {

    private TextView tvName, tvPass;

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

        tvName = findViewById(R.id.tvusername);
        tvPass = findViewById(R.id.tvpassword);

        tvName.setText(MainActivity.firstName);
        tvPass.setText(MainActivity.hobby);

    }
}

As you can see that, I have taken two text views.

These text views are getting their values with the help of two variables.

One is firstName and other is hobby.

These variables are defined in the MainActivity.java as the public identifier. Because these variables are public so we can use them in HobbyActivity.java file.

Step 3. Main Activity Files

When you have created new project in android studio, system must have created two files automatically.

One is activity_main.xml and other one is MainActivity.java

Source code for activity_main.xml is as the following

<?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:background="#edd712"
    android:gravity="center"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="45sp"
        android:text="DemoNuts"
        android:textColor="#fff"
        android:layout_marginBottom="20dp"/>

    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etusername"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Username" />
    <EditText
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/etpassword"
        android:inputType="textPassword"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_marginLeft="20dp"
        android:paddingLeft="5dp"
        android:background="#fff"
        android:hint="Enter Password" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/btn"
        android:text="Login"
        android:background="@color/colorPrimary"
        android:textColor="#fff"
        android:layout_marginTop="10dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"/>

</LinearLayout>

Main XML file will create one login template. Here user will insert the login credentials.

It includes One text view, two edit text and one button widget.

Text view is static and it includes the header name.

One edit text will receive the value of user name and other one will hold the value of password.

When the user will click the button, we will make the POST http call with parameters using volley library.

Now write down the following code block in MainActivity.java file.

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private String URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/simplelogin.php";

    private EditText etUname, etPass;
    private Button btn;
    public static String firstName, hobby;

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

        etUname = findViewById(R.id.etusername);
        etPass = findViewById(R.id.etpassword);
        btn = findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });

    }

    private void loginUser(){

      final String username = etUname.getText().toString().trim();
      final String password = etPass.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                        parseData(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put("username",username);
                params.put("password",password);

                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

    public void parseData(String response) {

        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++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

}

Looking Closely at Main Code

First of all, consider the below snippet

 private String URLline = "https://demonuts.com/Demonuts/JsonTest/Tennis/simplelogin.php";
 private EditText etUname, etPass;
 private Button btn;
 public static String firstName, hobby;

First line is the string variable. It include the URL in string format.

Second one is defining the objects of Edit text class and third one is giving us the object of Button class.

Fourth code line is making two public string variables. We have used these public variables in Hobby Activity also.

Now read the below code structure

  btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUser();
            }
        });
  • When the user clicks the button, compiler will call loginUser() method.

Coding lines for loginUser() method is as the following

private void loginUser(){

      final String username = etUname.getText().toString().trim();
      final String password = etPass.getText().toString().trim();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Toast.makeText(MainActivity.this,response,Toast.LENGTH_LONG).show();
                        parseData(response);

                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
                    }
                }){
            @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put("username",username);
                params.put("password",password);

                return params;
            }

        };

        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);
    }

Two string variables username and password are defined at the starting of this loginUser() method.

username will get it’s value in string format from etUname which is an edit text.

Other edit text etPass will give the value of password to the string variable password.

After this, compiler will create the object of the StringRequest class.

Look at the below line

 StringRequest stringRequest = new StringRequest(Request.Method.POST, URLline,

Here, Request.Method.POST will tell volley to make POST request.

URLline is the string variable which holds the full URL structure.

Now read the following source code

 @Override
            protected Map<String,String> getParams(){
                Map<String,String> params = new HashMap<String, String>();
                params.put("username",username);
                params.put("password",password);

                return params;
            }

Above code will create one hash map. This map has two children.

One is with key->”username” and value->string variable (username)

Another is with key ->”password” and value -> string variable (password)

This hash map will provide parameters to our URL.

After successful call to the web service, compiler will execute onResponse() method.

onResponse() method will create one Toast which will provide full JSON response.

After Toast, compiler will call parseData() method. Parameter for this method is the JSON response in the string format.

Code structure for parseData() method is as the following

 public void parseData(String response) {

        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++) {

                    JSONObject dataobj = dataArray.getJSONObject(i);
                    firstName = dataobj.getString("name");
                    hobby = dataobj.getString("hobby");
                }

                Intent intent = new Intent(MainActivity.this,HobbyActivity.class);
                startActivity(intent);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

    }

Here, compiler will first parse the JSON object.

Then it will check the field “status“. If it’s value is true then it will parse one JSON array.

Then it will create one for loop. Inside this for loop, compiler will parse first name and hobby.

And then it will save this first name and hobby in public string variables.

After for loop, system will open a new activity called “Hobby Activity”, which we have already created in Step 2.





3. Android JSON Parsing Using Volley And Display With RecyclerView

Android JSON Parsing Using Volley And Display With RecyclerView is today’s tutorial.

First of all, we will parse the JSON from URL using Volley.

Then we will populate a recyclerview using the data fetched from the JSON.

Generally, we need to make http calls to use the data on the remote server but volley simplifies this process.

Volley will reduce the number of Coding lines to make GET or POST calls to the web service.

We will fetch the information like name, country, city and image URL from the JSON.

Along with recyclerview, we will also use cardview to make it looking more attractive.

RecyclerView From Volley

Step 1. Internet Permission In Manifest

Internet is the basic requirement to call JSON from the remote server.

Add the below line in the AndroidManifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.parsaniahardik.json_recycler_volley">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        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>

Here, we do not need to code for runtime permissions because internet is the normal or basic permission.

Normal permission means that it is lesser harming to the user privacy.

Step 2. Some Dependencies

It is time write some dependencies in the build.gradle(Module: app) file as per the below

 implementation 'com.android.volley:volley:1.1.1'
 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'

I have added these lines for four different purposes.

First one is for volley library. It will enable us to use volley classes with any other integrations.

Second line is for picasso library which helps us to fetch the image from URL seamlessly.

Third line will allow us to use the recyclerview.

And finally, fourth line will give us the required classes for the usage of cardview.

Step 3. XML File For RecyclerView

Let us create an XML file under res->layout directory.

Give it a name rv_one.xml and add the following code in it

<?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>

This file will provide the view structure to every row of the recyclerview.

I have taken one imaheview and three textviews in this file.

All these widgets are under the cardview that will create card layout to every row item.

Step 4. Data Model

Let us create a new class and give it a name DataModel.java

Code structure for DataModel.java is as the following

public class DataModel {

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

Step 5. Required Adapter

Adapter class will help us to populate the recyclerview.

Make a new JAVA class and give it a name RvAdapter.java

Code block for RvAdapter.java is as the following block

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 RvAdapter extends RecyclerView.Adapter<RvAdapter.MyViewHolder> {

    private LayoutInflater inflater;
    private ArrayList<DataModel> dataModelArrayList;

    public RvAdapter(Context ctx, ArrayList<DataModel> dataModelArrayList){

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

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

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

        return holder;
    }

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

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

    @Override
    public int getItemCount() {
        return dataModelArrayList.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);
        }

    }
}

Consider the below lines

 private LayoutInflater inflater;
    private ArrayList<DataModel> dataModelArrayList;

    public RvAdapter(Context ctx, ArrayList<DataModel> dataModelArrayList){

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

First compiler will define the objects of LayoutInflater and arraylist.

Constructor will give us context and arraylist via it’s parameters.

Look at the following code block

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

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

First line is loading the Image from the URL.

Compiler will use Picasso library here. It will get the url using getter method.

Compiler will write the name, country and city using related getter methods from the objects of the arraylist.

Step 6. Main Modifications

Add the following lines in activity_main.xml file

<?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 Volley"
        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>

It includes one textview and recyclerview.

Now write down the following lines in MainActivity.java file

import android.app.ProgressDialog;
import android.content.Context;
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 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 static ProgressDialog mProgressDialog;
    ArrayList<DataModel> dataModelArrayList;
    private RvAdapter rvAdapter;
    private RecyclerView recyclerView;

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

        recyclerView = findViewById(R.id.recycler);

        fetchingJSON();

    }

    private void fetchingJSON() {

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

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

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

                        try {

                            removeSimpleProgressDialog();

                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

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

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

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

                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));
                                    playerModel.setImgURL(dataobj.getString("imgURL"));

                                    dataModelArrayList.add(playerModel);

                                }

                                setupRecycler();

                            }

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

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

        requestQueue.add(stringRequest);


    }

    private void setupRecycler(){

        rvAdapter = new RvAdapter(this,dataModelArrayList);
        recyclerView.setAdapter(rvAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

    }

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

}

Broad View Of Main Class

Read the below lines

private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
private static ProgressDialog mProgressDialog;
ArrayList<DataModel> dataModelArrayList;
private RvAdapter rvAdapter;
private RecyclerView recyclerView;

First line is defining the URL of the Web service.

We will parse JSON using this URL via volley.

Second line is making the object of the progrss bar.

Third one is creating an arraylist with the objects of the DataModel class.

Fourth is making on object of RvAdapter and fifth is of RecyclerView class.

Inside onCreate() method, compiler is calling fetchingJSON() method.

Following is the code structure for fetchingJSON() method.

 private void fetchingJSON() {

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

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

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

                        try {

                            removeSimpleProgressDialog();

                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

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

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

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

                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));
                                    playerModel.setImgURL(dataobj.getString("imgURL"));

                                    dataModelArrayList.add(playerModel);

                                }

                                setupRecycler();

                            }

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

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

        requestQueue.add(stringRequest);


    }
  • This method will parse the JSON and will populate the arraylist.

Json that it will parse is as the following

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

fetchingJSON() method will make an array (dataArray) using JSONArray class.

Then compiler will execute a for loop for the number of times equals to the number of items of the daraArray.

During every iteration, compiler will create one object of the DataModel class.

Then it will set the values using setter methods and finally, it will add the object into the arraylist (dataModelArrayList)

Then compiler will call the setupRecycler() method.

Code for setupRecycler() method is as the following

 private void setupRecycler(){

        rvAdapter = new RvAdapter(this,dataModelArrayList);
        recyclerView.setAdapter(rvAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false));

    }

In this method, compiler will create the objects of the RvAdapter class.

It will use dataModelArrayList while making this object.

At last, this adapter is set to the recyclerview and it will create recyclerview from JSON data.





4. Android ListView Using Volley | Parse JSON Listview

Android ListView Using Volley is the important aspect in android development.

In this tutorial, you will learn to parse JSON Data with Volley and Display in ListView With Image and Text.

We will retrieve mysql data from web server in JSON format and will make custom listview with image and text using volley.

Volley is the library that simplifies the process of fetching json data from mysql server or database.

We are creating a demo where we will retrieve data like county, city, name and image URL in string format.

Making listview from this data will be easy task if we maintain data with proper model class structure.

Video Output

Step 1. Adding Gradle Dependencies

To use volley in android app, we need to fetch various classes of the library in our project.

We can do this by adding volley’s gradle dependency.

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

 implementation 'com.android.volley:volley:1.1.1'
 implementation 'com.squareup.picasso:picasso:2.71828'

First line is the dependency for volley.

Second one is for Picasso library. We will use Picasso to load images from the URL.

Step 2. Permission To Use Internet

Internet is required to retrieve JSON data from remote server.

We have to write for Internet permission in AndroidManifest.xml file.

Copy the below line in AndroidManifest.xml

 <uses-permission android:name="android.permission.INTERNET"/>
  • Asking for runtime permission is not required here because internet permission is a normal permission.

Step 3. Class of Model

To maintain the proper data structure for ListView, model class can be a perfect component.

We can define getter and setter methods in this class for all the information here.

Create a new class named DataModel.java and fill the below source code

public class DataModel {

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

There are different types of information like name, country, city and image URL in string format.

Above class includes separate getter and setter methods for all data types.

These methods will help to reduce complexity of listview adapter class.

Step 4. Proper ListView Layout

To make same layout for all the child of listview, we have to make one layout file.

Make a new Layout XML file under res->Layout directory.

Set the name of the file as lv_player.xml and copy the following code in it.

<?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">

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

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

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_marginTop="5dp"
            android:layout_weight="1"
            android:id="@+id/name"
            android:text="ddd"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/country"
            android:text="ddd"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="0dp"
            android:layout_weight="1"
            android:id="@+id/city"
            android:text="ddd"/>

    </LinearLayout>

</LinearLayout>

One ImageView and three TextView are representing the above file.

Image from URL will be loaded in the ImageView and other information will fill the textviews.

Step 5. ListView Adapter

Adapter works as the data setter for the ListView.

It helps us to set the data in each row with proper manipulation of the data.

Prepare a new java class and give it a name ListAdapter.java

Source code for  ListAdapter.java is as the below

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;

public class ListAdapter extends BaseAdapter {

    private Context context;
    private ArrayList<DataModel> dataModelArrayList;

    public ListAdapter(Context context, ArrayList<DataModel> dataModelArrayList) {

        this.context = context;
        this.dataModelArrayList = dataModelArrayList;
    }

    @Override
    public int getViewTypeCount() {
        return getCount();
    }
    @Override
    public int getItemViewType(int position) {

        return position;
    }

    @Override
    public int getCount() {
        return dataModelArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return dataModelArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            holder = new ViewHolder();
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.lv_player, null, true);

            holder.iv = (ImageView) convertView.findViewById(R.id.iv);
            holder.tvname = (TextView) convertView.findViewById(R.id.name);
            holder.tvcountry = (TextView) convertView.findViewById(R.id.country);
            holder.tvcity = (TextView) convertView.findViewById(R.id.city);

            convertView.setTag(holder);
        }else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = (ViewHolder)convertView.getTag();
        }

        Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.tvname.setText("Name: "+dataModelArrayList.get(position).getName());
        holder.tvcountry.setText("Country: "+dataModelArrayList.get(position).getCountry());
        holder.tvcity.setText("City: "+dataModelArrayList.get(position).getCity());

        return convertView;
    }

    private class ViewHolder {

        protected TextView tvname, tvcountry, tvcity;
        protected ImageView iv;
    }

}

Understanding Adapter

Look at the below constructor

 public ListAdapter(Context context, ArrayList<DataModel> dataModelArrayList) {

        this.context = context;
        this.dataModelArrayList = dataModelArrayList;
    }

Adapter will get the arraylist (dataModelArrayList) made with the objects of DataModel via constructor.

This arraylist will help us to populate the listview.

Consider the following lines from getView() method.

  Picasso.get().load(dataModelArrayList.get(position).getImgURL()).into(holder.iv);
        holder.tvname.setText("Name: "+dataModelArrayList.get(position).getName());
        holder.tvcountry.setText("Country: "+dataModelArrayList.get(position).getCountry());
        holder.tvcity.setText("City: "+dataModelArrayList.get(position).getCity());

First line will load the image from URL using Picasso.

Compiler will set this image in imageview.

Then it will set the other information in the respective textviews.

As you may have noticed that arraylist (dataModelArrayList) is giving us proper object with the help of position.

Step 6. Climax Changes

Now we just need to change the main files and that is all.

Set the code of activity_main.xml file as the below one

<?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:layout_marginTop="10dp"
        android:text="Below ListView is populated from JSON Data"
        android:textColor="#000"
        />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/lv"
        android:layout_marginTop="10dp">


    </ListView>

</LinearLayout>

A textview in above snippet is suggesting that below listview is populated from json data.

Then a listview is present which holds the JSON data.

After this, source code for MainActivity.java is looking like the following

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
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 static ProgressDialog mProgressDialog;
    private ListView listView;
    ArrayList<DataModel> dataModelArrayList;
    private ListAdapter listAdapter;

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

        listView = findViewById(R.id.lv);

        retrieveJSON();

    }

    private void retrieveJSON() {

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

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

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

                        try {

                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

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

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

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

                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));
                                    playerModel.setImgURL(dataobj.getString("imgURL"));

                                    dataModelArrayList.add(playerModel);

                                }

                                setupListview();

                            }

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

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

        requestQueue.add(stringRequest);


    }

    private void setupListview(){
        removeSimpleProgressDialog();  //will remove progress dialog
        listAdapter = new ListAdapter(this, dataModelArrayList);
        listView.setAdapter(listAdapter);
    }

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

}

Entities of Main Activity

Let us check the modules of above class step by step.

Consider the below snippet

 private String URLstring = "https://demonuts.com/Demonuts/JsonTest/Tennis/json_parsing.php";
    private static ProgressDialog mProgressDialog;
    private ListView listView;
    ArrayList<DataModel> dataModelArrayList;
    private ListAdapter listAdapter;

First line is representing the URL line from where we will get the JSON data.

Second one will create an object of progress dialog.

Third is giving us the object of Listview.

Fourth one is making an arraylist of the objects of the DataModel class.

Last one is making an Adapter object.

In onCreate() method, compiler will call a method retrieveJSON().

Code block of retrieveJSON() method is as the following

private void retrieveJSON() {

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

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

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

                        try {

                            JSONObject obj = new JSONObject(response);
                            if(obj.optString("status").equals("true")){

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

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

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

                                    playerModel.setName(dataobj.getString("name"));
                                    playerModel.setCountry(dataobj.getString("country"));
                                    playerModel.setCity(dataobj.getString("city"));
                                    playerModel.setImgURL(dataobj.getString("imgURL"));

                                    dataModelArrayList.add(playerModel);

                                }

                                setupListview();

                            }

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

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

        requestQueue.add(stringRequest);


    }

Compiler will show the progress dialog to inform user that system is fetching the data from the server.

Then it will use stringRequest class of volley with URL to make http call to server.

In the try block, we will parse the JSON using JSONObject and JOSNArray classes.

JSON fetched from the URL looks 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"
        }
    ]
}

object named “status” will have true or false value.

If value is true then compiler will parse JSONArray called “data.”

One for loop is made up.

Number of iterations of for loop is equals to the number of object of “data” array.

During every iteration, compiler will set the data in the arraylist (dataModelArrayList).

After that, compiler will call setupListView() method.

Code for setupListView() method is as below

 private void setupListview(){
        removeSimpleProgressDialog();  //will remove progress dialog
        listAdapter = new ListAdapter(this, dataModelArrayList);
        listView.setAdapter(listAdapter);
    }

Compiler will first remove the progress dialog.

Then it will set the adapter to the listview. Adapter includes arraylist in it’s parameter.