Android - Extract Data From JSON Array using Retrofit Library with Jetpack Compose
Last Updated :
19 Jul, 2022
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. In this article, we will take a look at How to parse Data from JSON array in android using the Retrofit library with Jetpack Compose.
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. While choosing the template, select Empty Compose Activity. If you do not find this template, try upgrading the Android Studio to the latest version. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Adding dependency for using Retrofit
Navigate to app > Gradle Scripts > build.gradle file and add the below dependency to it.
// below dependency for using retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
After adding this dependency simply sync your project to install it.
Step 3: Adding a new color in the Color.kt file
Navigate to app > java > your app’s package name > ui.theme > Color.kt file and add the below code to it.
Kotlin
package com.example.newcanaryproject.ui.theme
import androidx.compose.ui.graphics.Color
val Purple200 = Color(0xFF0F9D58)
val Purple500 = Color(0xFF0F9D58)
val Purple700 = Color(0xFF3700B3)
val Teal200 = Color(0xFF03DAC5)
// on below line we are adding different colors.
val greenColor = Color(0xFF0F9D58)
Step 4: 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 5: Creating a Modal class
Navigate to app > java > your app's package name > Right-click on it > New > Kotlin class and specify the name of the class as ListModal and add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.example.newcanaryproject
// on below line we are creating a
// modal class for our data class.
data class ListModal(
// on below line we are creating two variable
// one is for language name which is string.
val languageName: String
)
Step 6: Creating an Interface
Navigate to app>java>your app's package name>Right click on it>New>Kotlin class and select interface in it and then specify the name as RetrofitAPI. Add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.example.newcanaryproject
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("T7R2")
fun
// as we are calling data from array so we are calling
// it with array list and naming that method as getAllCourses();
getLanguages(): Call<ArrayList<ListModal>>
}
Step 7: Working with MainActivity.kt file
Navigate to app>java>your app's package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail.
Kotlin
package com.example.newcanaryproject
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import com.example.newcanaryproject.ui.theme.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
NewCanaryProjectTheme {
// on below line we are specifying background color for our application
Surface(
// on below line we are specifying modifier and color for our app
modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
) {
// on the below line we are specifying the theme as scaffold.
Scaffold(
// in scaffold we are specifying top bar.
topBar = {
// inside top bar we are specifying background color.
TopAppBar(backgroundColor = greenColor,
// along with that we are specifying title for our top bar.
title = {
// in the top bar we are specifying tile as a text
Text(
// on below line we are specifying
// text to display in top app bar.
text = "JSON Parsing in Android",
// on below line we are specifying
// modifier to fill max width.
modifier = Modifier.fillMaxWidth(),
// on below line we are
// specifying text alignment.
textAlign = TextAlign.Center,
// on below line we are
// specifying color for our text.
color = Color.White
)
})
}) {
// on below line we are display list view
// method to display our list view.
displayListView()
}
}
}
}
}
}
fun getJSONData(courseList: MutableList<String>, ctx: Context) {
// 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.
.addConverterFactory(GsonConverterFactory.create())
// at last we are building our retrofit builder.
.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<ListModal>> = retrofitAPI.getLanguages()
// on below line we are calling method to enqueue and calling
// all the data from array list.
call!!.enqueue(object : Callback<ArrayList<ListModal>?> {
override fun onResponse(
call: Call<ArrayList<ListModal>?>,
response: Response<ArrayList<ListModal>?>
) {
// on below line we are checking if response is successful.
if (response.isSuccessful) {
// on below line we are creating a new list
var lst: ArrayList<ListModal> = ArrayList()
// on below line we are passing
// our response to our list
lst = response.body()!!
// on below line we are passing
// data from lst to course list.
for (i in 0 until lst.size) {
// on below line we are adding data to course list.
courseList.add(lst.get(i).languageName)
}
}
}
override fun onFailure(call: Call<ArrayList<ListModal>?>, t: Throwable) {
// displaying an error message in toast
Toast.makeText(ctx, "Fail to get the data..", Toast.LENGTH_SHORT)
.show()
}
})
}
@Composable
fun displayListView() {
val context = LocalContext.current
// on below line we are creating and
// initializing our array list
val courseList = remember { mutableStateListOf<String>() }
getJSONData(courseList, context)
// on the below line we are creating a
// lazy column for displaying a list view.
// on below line we are calling lazy column
// for displaying listview.
LazyColumn {
// on below line we are populating
// items for listview.
items(courseList) { language ->
// on below line we are specifying ui for each item of list view.
// we are specifying a simple text for each item of our list view.
Text(language, modifier = Modifier.padding(15.dp))
// on below line we are specifying
// divider for each list item
Divider()
}
}
}
Now run your application to see the output of it.
Output:
Similar Reads
Android - Extract Data From JSON Array using Volley Library with Jetpack Compose
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
5 min read
Android - Extract Data From JSON Array using Retrofit Library with Kotlin
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 O
7 min read
How to Extract Data from JSON Array in Android using Retrofit Library?
In the previous article on JSON Parsing in Android using Retrofit 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. Â Note
9 min read
Android - JSON Parsing Using Retrofit Library with Jetpack Compose
JSON is a format with the help of which we can exchange the data from the server within our application or a website. For accessing this data from the server within android applications. There are several libraries that are available such as Volley and Retrofit. In this article, we will take a look
9 min read
How to Extract Data from JSON Array in Android using Volley Library?
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 Ar
8 min read
Android - Extract Data From JSON Array using Volley Library with Kotlin
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
7 min read
Extract Data From PDF File using Android Jetpack Compose
PDF files are used in many android applications for displaying data in the form of images, text as well as graphics. Many applications are also required to get the data from this PDF file and display this data within the android application. So for extracting the data from PDF file pdf reader is use
3 min read
Android - JSON Parsing using Volley Library with Jetpack Compose
JSON is a JavaScript object notation which is a format to exchange the data from the server. JSON stores the data in a lightweight format. With the help of JSON, we can access the data in the form of JsonArray, JsonObject, and JsonStringer. In this article, we will specifically take a look at the im
8 min read
How to Post Data to API using Retrofit in Android using Jetpack Compose?
APIs are used within Android Applications to interact with databases to perform various CRUD operations on data within the database such as adding new data, reading the existing data, and updating and deleting existing data. In this article, we will take a look at How to Post Data to API using Retro
5 min read
How to Read Data From SQLite Database in Android using Jetpack Compose?
In the 1st part of our SQLite database, we have seen How to Create and Add Data to SQLite Database in Android using Jetpack Compose. In that article, we have added data to our SQLite Database. In this article, we will read all this data from the SQLite database and display this data in our ListView
8 min read