Open In App

Android – Extract Data From JSON Array using Volley Library with Kotlin

Last Updated : 22 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

JSON responses are of 2 types i.e. JSON Object and JSON Array. JSON Array consists of individual JSON objects which are having same similar structure but have different values within it. JSON Array is used to parse the data in the form of a list or an array. In the previous article, we have taken a look at How to extract data from JSON Object in Android with Kotlin. In this article, we will take a look at How to parse Data from JSON array in android using the Volley library in Kotlin. 

Note: If you are looking to extract data from JSON Array in android application using Volley in Java. Check out the following article: How to extract data from JSON array in android using Java

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin 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"?>
<!--on below line we are creating a swipe to refresh layout-->
<RelativeLayout
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    tools:context=".MainActivity">
 
    <!--recycler view for displaying data-->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/idRVCourses"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
 
    <!--progress bar for loading-->
    <ProgressBar
        android:id="@+id/idPBLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" />
 
</RelativeLayout>


Step 5: Creating a Modal class for storing our data

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

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
data class CourseRVModal(
    // on below line we are creating a two variable
    // one for course name and other for course image.
    var courseName: String,
    var courseImg: String
)


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
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    app:cardCornerRadius="5dp"
    app:cardElevation="4dp">
     
      <!--on below line we are creating a
        linear layout for grid view item-->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
 
        <!--on below line we are creating
            a simple image view-->
        <ImageView
            android:id="@+id/idIVCourse"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:layout_margin="8dp"
            android:padding="5dp"
            android:src="@mipmap/ic_launcher" />
 
        <!--on below line we are creating
            a simple text view-->
        <TextView
            android:id="@+id/idTVCourse"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_margin="5dp"
            android:padding="4dp"
            android:text="@string/app_name"
            android:textAlignment="textStart"
            android:textColor="@color/black"
            android:textStyle="bold"
            tools:ignore="RtlCompat" />
 
    </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 > Kotlin class and name it as CourseRVAdapter and add the below code to it. 

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.squareup.picasso.Picasso
 
// on below line we are creating a course rv adapter class.
class CourseRVAdapter(
    // on below line we are passing variables as course list and context
    private var courseList: ArrayList<CourseRVModal>,
    ) : RecyclerView.Adapter<CourseRVAdapter.CourseViewHolder>() {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): CourseRVAdapter.CourseViewHolder {
        // this method is use to inflate the layout file
        // which we have created for our recycler view.
        // on below line we are inflating our layout file.
        val itemView = LayoutInflater.from(parent.context).inflate(
            R.layout.course_rv_item,
            parent, false
        )
        // at last we are returning our view
        // holder class with our item View File.
        return CourseViewHolder(itemView)
    }
 
    override fun onBindViewHolder(holder: CourseRVAdapter.CourseViewHolder, position: Int) {
        // on below line we are setting data to our text view and our image view.
        holder.courseNameTV.text = courseList.get(position).courseName
        Picasso.get().load(courseList.get(position).courseImg).into(holder.courseIV)
    }
 
    override fun getItemCount(): Int {
        // on below line we are returning
        // our size of our list
        return courseList.size
    }
 
    class CourseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        // on below line we are initializing our course name
        // text view and our image view.
        val courseNameTV: TextView = itemView.findViewById(R.id.idTVCourse)
        val courseIV: ImageView = itemView.findViewById(R.id.idIVCourse)
    }
}


Step 8: Working with the MainActivity.kt file

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

Kotlin




package com.gtappdevelopers.kotlingfgproject
 
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.RecyclerView
import com.android.volley.Request
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
 
class MainActivity : AppCompatActivity() {
 
    // on below line we are creating variables.
    lateinit var courseRV: RecyclerView
    lateinit var loadingPB: ProgressBar
    lateinit var courseRVAdapter: CourseRVAdapter
    lateinit var courseList: ArrayList<CourseRVModal>
 
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
         
        // on below line we are initializing
        // our variable with their ids.
        courseRV = findViewById(R.id.idRVCourses)
        loadingPB = findViewById(R.id.idPBLoading)
 
        // on below line we are initializing our list
        courseList = ArrayList()
 
        // on below line we are initializing our adapter.
        courseRVAdapter = CourseRVAdapter(courseList)
 
        // on below line we are setting
        // adapter to recycler view.
        courseRV.adapter = courseRVAdapter
 
        // on below line we are calling
        // get data method to get data.
        getData()
 
    }
 
    private fun getData() {
        // on below line we are creating a variable for url
        var url = "https://jsonkeeper.com/b/0RH6"
 
        // on below line we are creating a
        // variable for our request queue
        val queue = Volley.newRequestQueue(this@MainActivity)
 
        // on below line we are creating a request
        // variable for making our json object request.
        val request =
            // as we are getting json object response and we are making a get request.
            JsonArrayRequest(Request.Method.GET, url, null, { response ->
                // this method is called when we get successful response from API.
                loadingPB.visibility = View.GONE
                try {
                    for (i in 0 until response.length()) {
                        // on below line we are extracting
                        // data from each json object
                        val respObj = response.getJSONObject(i)
                        val lngName = respObj.getString("languageName")
                        val lngImg = respObj.getString("languageImg")
 
                        // on below line we are adding data to our list
                        courseList.add(CourseRVModal(lngName, lngImg))
 
                        // on below line we are notifying
                        // our adapter that data has updated.
                        courseRVAdapter.notifyDataSetChanged()
                    }
 
                  // on below line we
                  // are handling exception
                } catch (e: Exception) {
                    e.printStackTrace()
                }
 
            }, { error ->
                // in this case we are simply displaying a toast message.
                Toast.makeText(this@MainActivity, "Fail to get response", Toast.LENGTH_SHORT)
                    .show()
            })
        // at last we are adding our
        // request to our queue.
        queue.add(request)
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads