Open In App

Android – Extract Data From JSON Array using Retrofit Library with Jetpack Compose

Last Updated : 19 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. 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:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads