JSON GET Request in Android Using Volley

Introduction 

 
In this article, we are going to see how to perform a simple JSON get request in Android using the Volley library. 
 

What is Volley?

 
Volley is an HTTP library that makes networking for Android apps easier and most importantly, faster. Google introduced Volley during Google I/O 2013.
 
Documentation - https://developer.android.com/training/volley
 

What is Picasso

 
A powerful image downloading and caching library for Android.
 
Documentation - https://square.github.io/picasso/
 

PROJECT SETUP

  1. Create a new Android project in android studio with the language selected as Java.
  2. Add the following dependency in Gradle: 
For Picasso:
  1. implementation 'com.squareup.picasso:picasso:(insert latest version)' 
For Volley:
  1. implementation 'com.android.volley:volley:1.1.1'  

Development Steps

 
Step 1
 
Add the list view to the activity_main.xml file by adding this following xml code:
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"    
  4.     xmlns:tools="http://schemas.android.com/tools"    
  5.     android:layout_width="match_parent"    
  6.     android:layout_height="match_parent"    
  7.         
  8.     tools:context=".MainActivity">    
  9.     
  10.    <ListView    
  11.        android:layout_width="match_parent"    
  12.        android:layout_height="match_parent"    
  13.        android:id="@+id/musiclistview"    
  14.        />    
  15.     
  16. </RelativeLayout>   
Step 2
 
Create a custom layout for our custom listview row by adding a new XML with name customcell.xml in res project folder.
 
Step 3
 
Add the following xml code in customcell.xml file:
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     android:layout_width="match_parent" android:layout_height="match_parent">    
  4. <ImageView    
  5.     android:layout_width="200dp"    
  6.     android:layout_height="200dp"    
  7.     android:layout_alignParentLeft="true"    
  8.     android:layout_alignParentTop="true"    
  9.     android:id="@+id/albumcoverimageview"    
  10.     android:src="@drawable/ic_launcher_background"/>    
  11.     
  12.     <TextView    
  13.         android:layout_width="wrap_content"    
  14.         android:id="@+id/albumnamelbl"    
  15.         android:layout_height="wrap_content"    
  16.         android:layout_alignParentLeft="true"    
  17.         android:layout_alignParentTop="true"    
  18.         android:layout_centerHorizontal="true"    
  19.         android:layout_marginLeft="214dp"    
  20.         android:textColor="@android:color/black"    
  21.         android:layout_marginTop="68dp"    
  22.         android:text="Album name"    
  23.         android:textSize="30sp" />    
  24. </RelativeLayout>    
We have created the below layout for our custom cell for our list view:
 
 
Step 4
 
Create a new Java class named Album.java which acts as a data model for our list view data source.
 
Step 5
 
Add the following code:
  1. public class Albums {  
  2.   
  3.     public String albumname;  
  4.     public String albumcoverurl;  
  5.   
  6.     Albums(String albumname,String albumcoverurl)  
  7.     {  
  8.         this.albumname = albumname;  
  9.         this.albumcoverurl = albumcoverurl;  
  10.     }  
  11.   
  12.     public String getAlbumcoverurl() {  
  13.         return albumcoverurl;  
  14.     }  
  15.   
  16.     public String getAlbumname() {  
  17.         return albumname;  
  18.     }  

Step 6
 
The next step is to create a custom ArrayAdapter that can be used to provide our custom cell layout to our Custom listview.
 
Step 7
 
Create a new Java class called MyAdapter.java which extends the ArrayAdapter class.
 
Step 8
 
Add the following code:
 
Here we override a method getView which returns a view that has our inflated custom cell layout.
  1. package com.enigmacoder.jsonget;  
  2. import android.content.Context;    
  3. import android.view.LayoutInflater;    
  4. import android.view.View;    
  5. import android.view.ViewGroup;    
  6. import android.widget.ArrayAdapter;    
  7. import android.widget.ImageView;    
  8. import android.widget.TextView;   
  9. import androidx.annotation.NonNull;    
  10. import androidx.annotation.Nullable;  
  11. import com.squareup.picasso.Picasso;  
  12. import java.util.List;  
  13. public class MyAdapter extends ArrayAdapter<Albums> {  
  14.     Context context;    
  15.     int resource;    
  16.     List<Albums> albumsList;  
  17.     MyAdapter(Context context,int resource,List<Albums> albumsList)    
  18.     {  
  19.         super(context,resource,albumsList);    
  20.         this.context = context;    
  21.         this.resource = resource;    
  22.         this.albumsList = albumsList;    
  23.     }  
  24.     @NonNull    
  25.     @Override    
  26.     public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {    
  27.         LayoutInflater inflater = LayoutInflater.from(context);    
  28.         View view = inflater.inflate(resource,null,false);    
  29.         TextView aname = view.findViewById(R.id.albumnamelbl);    
  30.         ImageView aimage = view.findViewById(R.id.albumcoverimageview);    
  31.         Albums album = albumsList.get(position);    
  32.         aname.setText(album.getAlbumname());     
  33.         Picasso.with(context).load(album.getAlbumcoverurl()).into(aimage);  
  34.         return view;    
  35.     }    
  36. }  
 
Step 9
 
Open MainActivity.java and add the following Java code:
  1. package 'YOUR_PACKAGE_NAME';    
  2. import androidx.appcompat.app.AppCompatActivity;    
  3. import android.os.Bundle;    
  4. import android.widget.ListView;    
  5. import android.widget.Toast;  
  6. import com.android.volley.Request;    
  7. import com.android.volley.RequestQueue;    
  8. import com.android.volley.Response;    
  9. import com.android.volley.VolleyError;    
  10. import com.android.volley.toolbox.JsonArrayRequest;    
  11. import com.android.volley.toolbox.Volley;  
  12. import org.json.JSONArray;    
  13. import org.json.JSONObject;  
  14. import java.util.ArrayList;    
  15. import java.util.List;    
  16.     
  17. public class MainActivity extends AppCompatActivity {    
  18.     ListView musiclist;    
  19.     final String url = "https://rallycoding.herokuapp.com/api/music_albums";    
  20.     List<Albums> alist;    
  21.     MyAdapter adapter;    
  22.     RequestQueue requestQueue;    
  23.     @Override    
  24.     protected void onCreate(Bundle savedInstanceState) {    
  25.         super.onCreate(savedInstanceState);    
  26.         setContentView(R.layout.activity_main);    
  27.         musiclist = findViewById(R.id.musiclistview);    
  28.         alist = new ArrayList<>();    
  29.         requestQueue = Volley.newRequestQueue(this);//This will take care of    
  30.         //background newtwork activities    
  31.         getdata();  
  32.         adapter = new MyAdapter(this,R.layout.customcell,alist);    
  33.         musiclist.setAdapter(adapter);  
  34.     }  
  35.     private void getdata()    
  36.     {    
  37.         JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, nullnew Response.Listener<JSONArray>() {    
  38.             @Override    
  39.             public void onResponse(JSONArray response) {  
  40.                 JSONArray jsonArray = response;  
  41.                 try {  
  42.                     for(int i=0;i<jsonArray.length();i++)    
  43.                     {    
  44.                         JSONObject jsonObject = jsonArray.getJSONObject(i);    
  45.                         String albumname = jsonObject.getString("title");    
  46.                         String albumimageurl = jsonObject.getString("image");   
  47.                         alist.add(new Albums(albumname,albumimageurl));  
  48.                     }  
  49.                     adapter.notifyDataSetChanged();//To prevent app from crashing when updating    
  50.                     //UI through background Thread  
  51.                 }  
  52.                 catch (Exception w)    
  53.                 {    
  54.                     Toast.makeText(MainActivity.this,w.getMessage(),Toast.LENGTH_LONG).show();    
  55.                 }  
  56.             }    
  57.         }, new Response.ErrorListener() {    
  58.             @Override    
  59.             public void onErrorResponse(VolleyError error) {    
  60.                 Toast.makeText(MainActivity.this,error.getMessage(),Toast.LENGTH_LONG).show();    
  61.             }    
  62.         });  
  63.         requestQueue.add(jsonArrayRequest);  
  64.     }    
  65. }  
 
MAKE SURE YOU PLACE YOUR PACKAGE NAME IN THE FIRST LINE OF THE CODE.
 
In the above Java code, we create a request queue that can handle all the background network activities.
 
For more information about a get request using Volley, refer the documentation
 
https://developer.android.com/training/volley/request
  
Step 10
 
The next step is to add required permissions for our app in the AndroidManifest.xml file:
  1. <uses-permission android:name="android.permission.INTERNET"/> 
Now run your app.
 
You will see the following output:
 
The app makes a GET request to the server and retrieves the data in JSON format which displays it in the list view
 


Similar Articles