Open In App

How to Extract Data from JSON Array in Android using Volley Library?

Improve
Improve
Like Article
Like
Save
Share
Report

In the previous article on JSON Parsing in Android using Volley Library, we have seen how we can get the data from JSON Object in our android app and display that JSON Object in our app. In this article, we will take a look at How to extract data from JSON Array and display that in our app. 

JSON Array: JSON Array is a set or called a collection of data that holds multiple JSON Objects with similar sort of data. JSON Array can be easily identified with “[” braces opening and “]” braces closing. A JSON array is having multiple JSON objects which are having similar data. And each JSON object is having data stored in the form of key and value pair. 

What we are going to build in this article?  

We will be building a simple application in which we will be displaying a list of CardView in which we will display some courses which are available on Geeks for Geeks. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Below is our JSON array from which we will be displaying the data in our Android App. 

[

  {

     “courseName”:”Fork CPP”,

     “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/fork-cpp-thumbnail.png”,

     “courseMode”:”Online Batch”,

     “courseTracks”:”6 Tracks”

  },

  {

     “courseName”:”Linux & Shell Scripting Foundation”,

     “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/linux-shell-scripting-thumbnail.png”,

     “courseMode”:”Online Batch”,

     “courseTracks”:”8 Tracks”

  },

  {

     “courseName”:”11 Weeks Workshop on Data Structures and Algorithms”,

     “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/Workshop-DSA-thumbnail.png”,

     “courseMode”:”Online Batch”,

     “courseTracks”:”47 Tracks”

  },

  {

     “courseName”:”Data Structures and Algorithms”,

     “courseimg”:”https://media.geeksforgeeks.org/img-practice/banner/dsa-self-paced-thumbnail.png”,

     “courseMode”:”Online Batch”,

     “courseTracks”:”24 Tracks”

  }

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.

Step 2: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section. We have used the Picasso dependency for image loading from the URL.   

// below line is used for volley library

implementation ‘com.android.volley:volley:1.1.1’

// below line is used for image loading library

implementation ‘com.squareup.picasso:picasso:2.71828’

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

Step 3: Adding permissions to the internet in the AndroidManifest.xml file

Navigate to the app > AndroidManifest.xml and add the below code to it. 

XML




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


Step 4: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--progress bar for loading indicator-->
    <ProgressBar
        android:id="@+id/idPB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
  
    <!--recycler view to display our data-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone" />
      
</RelativeLayout>


Step 5: Creating a Modal class for storing our data

For storing our data we have to create a new java class. For creating a new java class, Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseModal and add the below code to it. Comments are added inside the code to understand the code in more detail.

Java




public class CourseModal {
  
    // variables for our course 
    // name and description.
    private String courseName;
    private String courseimg;
    private String courseMode;
    private String courseTracks;
  
    // creating constructor for our variables.
    public CourseModal(String courseName, String courseimg, String courseMode, String courseTracks) {
        this.courseName = courseName;
        this.courseimg = courseimg;
        this.courseMode = courseMode;
        this.courseTracks = courseTracks;
    }
  
    // creating getter and setter methods.
    public String getCourseName() {
        return courseName;
    }
  
    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }
  
    public String getCourseimg() {
        return courseimg;
    }
  
    public void setCourseimg(String courseimg) {
        this.courseimg = courseimg;
    }
  
    public String getCourseMode() {
        return courseMode;
    }
  
    public void setCourseMode(String courseMode) {
        this.courseMode = courseMode;
    }
  
    public String getCourseTracks() {
        return courseTracks;
    }
  
    public void setCourseTracks(String courseTracks) {
        this.courseTracks = courseTracks;
    }
}


Step 6: Creating a layout file for each item of our RecyclerView

Navigate to the app > res > layout > Right-click on it > New > layout resource file and give the file name as course_rv_item and add the below code to it. Comments are added in the code to get to know in more detail. 

XML




<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:elevation="8dp"
    app:cardCornerRadius="8dp">
  
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
  
        <!--ImageView to display our course image-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:layout_margin="5dp" />
  
        <!--text view for our course name-->
        <TextView
            android:id="@+id/idTVCourseName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:padding="5dp"
            android:text="Course Name "
            android:textColor="@color/black"
            android:textSize="18sp"
            android:textStyle="bold" />
  
        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:orientation="horizontal"
            android:weightSum="2">
  
            <!--text view for our batch name-->
            <TextView
                android:id="@+id/idTVBatch"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                android:text="Batch"
                android:textColor="@color/black" />
  
            <!--text view to display course tracks-->
            <TextView
                android:id="@+id/idTVTracks"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:padding="5dp"
                android:text="Tracks"
                android:textColor="@color/black" />
        </LinearLayout>
          
    </LinearLayout>
      
</androidx.cardview.widget.CardView>


Step 7: Creating an Adapter class for setting data to our RecyclerView item

For creating a new Adapter class navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as CourseAdapter and add the below code to it. 

Java




import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
  
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
  
import com.squareup.picasso.Picasso;
  
import java.util.ArrayList;
  
public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.ViewHolder> {
      
    // creating a variable for array list and context.
    private ArrayList<CourseModal> courseModalArrayList;
    private Context context;
  
    // creating a constructor for our variables.
    public CourseAdapter(ArrayList<CourseModal> courseModalArrayList, Context context) {
        this.courseModalArrayList = courseModalArrayList;
        this.context = context;
    }
  
    @NonNull
    @Override
    public CourseAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // below line is to inflate our layout.
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_rv_item, parent, false);
        return new ViewHolder(view);
    }
  
    @Override
    public void onBindViewHolder(@NonNull CourseAdapter.ViewHolder holder, int position) {
        // setting data to our views of recycler view.
        CourseModal modal = courseModalArrayList.get(position);
        holder.courseNameTV.setText(modal.getCourseName());
        holder.courseTracksTV.setText(modal.getCourseTracks());
        holder.courseModeTV.setText(modal.getCourseMode());
        Picasso.get().load(modal.getCourseimg()).into(holder.courseIV);
    }
  
    @Override
    public int getItemCount() {
        // returning the size of array list.
        return courseModalArrayList.size();
    }
  
    public class ViewHolder extends RecyclerView.ViewHolder {
        // creating variables for our views.
        private TextView courseNameTV, courseModeTV, courseTracksTV;
        private ImageView courseIV;
  
        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            
            // initializing our views with their ids.
            courseNameTV = itemView.findViewById(R.id.idTVCourseName);
            courseModeTV = itemView.findViewById(R.id.idTVBatch);
            courseTracksTV = itemView.findViewById(R.id.idTVTracks);
            courseIV = itemView.findViewById(R.id.idIVCourse);
        }
    }
}


Step 8: Working with the MainActivity.java file

Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.

Java




import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
  
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.JsonArrayRequest;
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 {
  
    // creating variables for 
    // our ui components.
    private RecyclerView courseRV;
      
    // variable for our adapter 
    // class and array list
    private CourseAdapter adapter;
    private ArrayList<CourseModal> courseModalArrayList;
     
    // below line is the variable for url from
    // where we will be querying our data.
    String url = "https://jsonkeeper.com/b/WO6S";
    private ProgressBar progressBar;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our variables.
        courseRV = findViewById(R.id.idRVCourses);
        progressBar = findViewById(R.id.idPB);
          
        // below line we are creating a new array list
        courseModalArrayList = new ArrayList<>();
        getData();
          
        // calling method to 
        // build recycler view.
        buildRecyclerView();
    }
  
    private void getData() {
        // creating a new variable for our request queue
        RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
        // in this case the data we are getting is in the form
        // of array so we are making a json array request.
        // below is the line where we are making an json array 
        // request and then extracting data from each json object.
        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                progressBar.setVisibility(View.GONE);
                courseRV.setVisibility(View.VISIBLE);
                for (int i = 0; i < response.length(); i++) {
                    // creating a new json object and 
                    // getting each object from our json array.
                    try {
                        // we are getting each json object.
                        JSONObject responseObj = response.getJSONObject(i);
                          
                        // now we get our response from API in json object format.
                        // in below line we are extracting a string with
                        // its key value from our json object.
                        // similarly we are extracting all the strings from our json object.
                        String courseName = responseObj.getString("courseName");
                        String courseTracks = responseObj.getString("courseTracks");
                        String courseMode = responseObj.getString("courseMode");
                        String courseImageURL = responseObj.getString("courseimg");
                        courseModalArrayList.add(new CourseModal(courseName, courseImageURL, courseMode, courseTracks));
                        buildRecyclerView();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(jsonArrayRequest);
    }
  
    private void buildRecyclerView() {
  
        // initializing our adapter class.
        adapter = new CourseAdapter(courseModalArrayList, MainActivity.this);
         
        // adding layout manager 
        // to our recycler view.
        LinearLayoutManager manager = new LinearLayoutManager(this);
        courseRV.setHasFixedSize(true);
          
        // setting layout manager 
        // to our recycler view.
        courseRV.setLayoutManager(manager);
          
        // setting adapter to 
        // our recycler view.
        courseRV.setAdapter(adapter);
    }
}


Now run your app and see the output of the app.

Output:



Last Updated : 28 Jan, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads