Android Tutorial on Volley library – How to Fetching JSON Data from URL
Android Tutorial on Volley library – How to Fetching JSON Data from URL

Hey guys, welcome to Proto Coders Point. This Tutorial post is all about implementing Android Volley Library Tutorial. I have a URL on our website  that gives me some JSON format data, and by using Volley library we will get those data, and we will also parse it. Ok So if you want to learn how to fetch json data from a URL in android and display it in Listview then let’s start this Android Tutorial on Volley library.

Before Starting Implementation let us know Basic of Volley Library.

What is Android Volley?

If you are new in android then you might be thinking what is this Volley library?

Volley is an HTTP library that makes networking very easy and fast, for Android application development.

What are benefits of  Android Volley?

  • Easy to use request management
  • Fast in fetching data from Any network.
  • Efficient network management
  • Easily customizable according to our need.

Android Tutorial on Volley library Implementation in android Studio.

Demo Output of android volley Library project

android volley library tutorial project
android volley library tutorial project

Now it’s time for implement library, As i have told you above that i have a  URL that contain JSON Data Format.

https://protocoderspoint.com/jsondata/superheros.json

Then if you are implementing this project then you can use same URL for your project Practice or Create your own JSON Data.

If you open the above URL, you will see the following JSON DATA .

{
  "superheros": [
    {
      "name": "Flash",
      "power": "Speed Run :.............."
    },
    {
      "name": "Super Man",
      "power": "the powers of flight, ................."
    },
    {
      "name": "Thor",
      "power": "Superhuman strength, ........"
    },
    {
        "name":"Hulk",
        "power":"Incredible superhuman strength, ......."
    },
    {
        "name":"Vemon",
        "power":"Venom also has super strength — ........"
    }
  ]
}

Now As you can see in above Screenshot Image we have some JSON data. At first, we have a JSON object { }, then inside that object, we have a key name superheros which contain array of JSON objects. Each object in the array has two more keys name and power. So In this android project our task is that to fetch this data and display it into a custom ListView.

Creating a new project under android-studio

As always the basic step in any development if creating a new Project.

when the project is been created successfully, we need to add uses-permission with INTERNET as we are about to perform a network Data fetch operation and it requires internet permission.

Adding internet Permission

Open the AndroidManifest.xml file under you project and  you need to add internet permission as shown below.

For your application to work freely on Android Pie ( 9 ) and above you need to add uses-library org.apache.http.legacy inside application tag

Check out below screenshot for this

uses-library org.apache.http.legacy
uses-library org.apache.http.legacy

Adding Volley Library

This is the very important step. As we are going to use volley library.

adding android volley library
adding android volley library

navigate towords project

Gradle Scripts > build gradle (Module:app) > under dependencies add below lines of codes

dependencies {
    ..................
    ................
    implementation 'com.android.volley:volley:1.1.1'
}

Now, you need to sync your android project and then its done with adding volley library into you project.

Create a Data Model Class

Data Model Class is used to store the fetched data in objects. So create a class named SuperHeros.java and then copy down the below lines of codes.

package protocoderspoint.com.volleyandroidpractices;

public class SuperHero {
    String name, power;

    public SuperHero(String name, String power) {
        this.name = name;
        this.power = power;
    }

    public String getName() {
        return name;
    }

    public String getPower() {
        return power;
    }
}

Creating a UI Design with ListView

  • So i previously  told you that we are going to fetch the data and show the data in a listView. So we are creating a Custom Listview to show data.

Copy paste the below lines of code inside activity_main.xml.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ProgressBar
        android:visibility="gone"
        android:id="@+id/progressBar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

</RelativeLayout>

As you can see that i have used ProgressBar that because when the fetching of data is going on we can show a progress bar until the data is fetched completed.

Then we would need a layout for our list items.

Inside the layout directory (res->layout)  you need to create a new layout resource file and name it  i have named it as list_items.xml.

<?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:padding="16dp"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAppearance="@style/Base.TextAppearance.AppCompat.Large" />

    <TextView
        android:id="@+id/textViewPower"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:autoLink="web"
        android:textColor="#08308e" />

</LinearLayout>

Here we have two string items i.e (name and power) in our json data, So we created two TextViews here to display the fetched data here.

Creating a Custom Adapter for listview

For this you need to create a new java class,i have named it as ListViewAdapter.java and copy the below code in that java Adapter class .

package protocoderspoint.com.volleyandroidpractices;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

import java.util.List;

public class ListViewAdopter extends ArrayAdapter<SuperHero> {

    //the hero list that will be displayed
    private List<SuperHero> superHeroList;

    //the context object
    private Context mCtx;

    //here we are getting the herolist and context
    //so while creating the object of this adapter class we need to give herolist and context
    public ListViewAdopter(List<SuperHero> superHeroList, Context mCtx) {
        super(mCtx, R.layout.list_items, superHeroList);
        this.superHeroList = superHeroList;
        this.mCtx = mCtx;
    }

    //this method will return the list item
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        //getting the layoutinflater
        LayoutInflater inflater = LayoutInflater.from(mCtx);

        //creating a view with our xml layout
        View listViewItem = inflater.inflate(R.layout.list_items, null, true);

        //getting text views
        TextView textViewName = listViewItem.findViewById(R.id.textViewName);
        TextView textViewImageUrl = listViewItem.findViewById(R.id.textViewPower);

        //Getting the superHero for the specified position
        SuperHero superHero = superHeroList.get(position);

        //setting superHero values to textviews
        textViewName.setText(superHero.getName());
        textViewImageUrl.setText(superHero.getPower());

        //returning the listitem
        return listViewItem;
    }
}

Now we are in the last part  that is fetching and parsing the json and displaying it to the ListView.

Fetching JSON Data from URL

Open MainActivity.java file  and paste the below lines of code.

package protocoderspoint.com.volleyandroidpractices;


import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

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;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    //the URL having the json data
    private static final String JSON_URL = "https://protocoderspoint.com/jsondata/superheros.json";

    //listview object
    ListView listView;

    //the hero list where we will store all the hero objects after parsing json
    List<SuperHero> superHeroList;

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

        //initializing listview and hero list
        listView = (ListView) findViewById(R.id.listView);
        superHeroList = new ArrayList<>();

        //this method will fetch and parse the data
        loadHeroList();
    }

    private void loadHeroList() {
        //getting the progressbar
        final ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar);

        //making the progressbar visible
        progressBar.setVisibility(View.VISIBLE);

        //creating a string request to send request to the url
        StringRequest stringRequest = new StringRequest(Request.Method.GET, JSON_URL,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        //hiding the progressbar after completion
                        progressBar.setVisibility(View.INVISIBLE);
                        Log.d("Json Response",response);


                        try {
                            //getting the whole json object from the response
                            JSONObject obj = new JSONObject(response);

                            //we have the array named hero inside the object
                            //so here we are getting that json array
                            JSONArray heroArray = obj.getJSONArray("superheros");

                            //now looping through all the elements of the json array
                            for (int i = 0; i < heroArray.length(); i++) {
                                //getting the json object of the particular index inside the array
                                JSONObject heroObject = heroArray.getJSONObject(i);

                                //creating a superHero object and giving them the values from json object
                                SuperHero superHero = new SuperHero(heroObject.getString("name"), heroObject.getString("power"));

                                //adding the superHero to herolist
                                superHeroList.add(superHero);
                            }

                            //creating custom adapter object
                            ListViewAdopter adapter = new ListViewAdopter(superHeroList, getApplicationContext());

                            //adding the adapter to listview
                            listView.setAdapter(adapter);

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

 

6 Comments