Open In App

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

Last Updated : 30 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In the android application, the response from the server is in the form of JSON. We can get to see either a JSON Array or a JSON Object in the response. JSON Array is the list of data which is having similar JSON objects. In the previous article, we have taken a look at How to parse data from JSON Object in android applications using Kotlin. In this article, we will take a look at How to Extract Data from JSON Array in Android using the Retrofit library in Kotlin. 

Note: If you are looking to extract data from JSON Array in an android application using the Retrofit library in Java. Check out the following article: How to Extract Data from JSON Array in Android using the Retrofit library with 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 dependency for using retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

// below dependency for using picasso 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. Comments are added inside the code to understand the code in more detail.

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

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 
    // two variable one for 
    // course name and other for course image.
    var languageName: String,
    var languageImg: 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. 

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).languageName
        Picasso.get().load(courseList.get(position).languageImg).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: Creating an interface class for writing our API calls

Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class select it as Interface and name the file as RetrofitAPI 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
  
import retrofit2.Call
import retrofit2.http.GET
  
interface RetrofitAPI {
  
    // as we are making get request 
    // so we are displaying
    // GET as annotation.
    // and inside we are passing last parameter for our url.
    @GET("0RH6")
    fun getAllCourses(): Call<ArrayList<CourseRVModal>?>?
}


Step 9: 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 retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
  
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 calling 
        // get all courses method to get data.
        getAllCourses()
  
    }
  
    private fun getAllCourses() {
        // on below line we are creating a retrofit
        // builder and passing our base url
        val retrofit = Retrofit.Builder()
            .baseUrl("https://jsonkeeper.com/b/"
             // on below line we are calling add
             // Converter factory as Gson converter factory.
             // at last we are building our retrofit builder.
            .addConverterFactory(GsonConverterFactory.create()) 
            .build()
  
        // below line is to create an instance for our retrofit api class.
        val retrofitAPI = retrofit.create(RetrofitAPI::class.java)
  
        // on below line we are calling a method to get all the courses from API.
        val call: Call<ArrayList<CourseRVModal>?>? = retrofitAPI.getAllCourses()
  
        // on below line we are calling method to enqueue and calling
        // all the data from array list.
        call!!.enqueue(object : Callback<ArrayList<CourseRVModal>?> {
            override fun onResponse(
                call: Call<ArrayList<CourseRVModal>?>,
                response: Response<ArrayList<CourseRVModal>?>
            ) {
                if (response.isSuccessful) {
                    loadingPB.visibility = View.GONE
                    courseList = response.body()!!
                }
  
                // on below line we are initializing our adapter.
                courseRVAdapter = CourseRVAdapter(courseList)
  
                // on below line we are setting adapter to recycler view.
                courseRV.adapter = courseRVAdapter
  
            }
  
            override fun onFailure(call: Call<ArrayList<CourseRVModal>?>, t: Throwable) {
                // displaying an error message in toast
                Toast.makeText(this@MainActivity, "Fail to get the data..", Toast.LENGTH_SHORT)
                    .show()
            }
        })
    }
}


Now run your application to see the output of it. 

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads