Android – Extract Data From JSON Array using Retrofit Library with Kotlin
Last Updated :
30 Jun, 2022
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
< 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" ?>
< RelativeLayout
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:fillViewport = "true"
android:orientation = "vertical"
tools:context = ".MainActivity" >
< androidx.recyclerview.widget.RecyclerView
android:id = "@+id/idRVCourses"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
app:layoutManager = "androidx.recyclerview.widget.LinearLayoutManager" />
< 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(
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
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:layout_gravity = "center"
android:layout_margin = "5dp"
app:cardCornerRadius = "5dp"
app:cardElevation = "4dp" >
< LinearLayout
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:orientation = "horizontal" >
< 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" />
< 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
class CourseRVAdapter(
private var courseList: ArrayList<CourseRVModal>,
) : RecyclerView.Adapter<CourseRVAdapter.CourseViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CourseRVAdapter.CourseViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.course_rv_item,
parent, false
)
return CourseViewHolder(itemView)
}
override fun onBindViewHolder(holder: CourseRVAdapter.CourseViewHolder, position: Int) {
holder.courseNameTV.text = courseList.get(position).languageName
Picasso.get().load(courseList.get(position).languageImg).into(holder.courseIV)
}
override fun getItemCount(): Int {
return courseList.size
}
class CourseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
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 {
@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() {
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)
courseRV = findViewById(R.id.idRVCourses)
loadingPB = findViewById(R.id.idPBLoading)
courseList = ArrayList()
getAllCourses()
}
private fun getAllCourses() {
val retrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.build()
val retrofitAPI = retrofit.create(RetrofitAPI:: class .java)
val call: Call<ArrayList<CourseRVModal>?>? = retrofitAPI.getAllCourses()
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()!!
}
courseRVAdapter = CourseRVAdapter(courseList)
courseRV.adapter = courseRVAdapter
}
override fun onFailure(call: Call<ArrayList<CourseRVModal>?>, t: Throwable) {
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
Share your thoughts in the comments
Please Login to comment...