Open In App

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

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 Volley 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 Volley

Navigate to app > Gradle Scripts > build.gradle file and add the below dependency to it. 

// dependency for volley
implementation 'com.android.volley:volley:1.2.0'

Now syn your project to install the dependency. 

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: 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.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.android.volley.Request
import com.android.volley.toolbox.JsonArrayRequest
import com.android.volley.toolbox.Volley
import com.example.newcanaryproject.ui.theme.*
 
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 below line we are specifying 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 parseJSONArray(courseList: MutableList<String>, ctx: Context) {
 
    // on below line we are creating a variable for url
    var url = "https://jsonkeeper.com/b/T7R2"
 
    // on below line we are creating a
    // variable for our request queue
    val queue = Volley.newRequestQueue(ctx)
 
    // 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.
            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")
 
                    // on below line we are adding data to our list
                    courseList += lngName
                }
                // 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(ctx, "Fail to get response", Toast.LENGTH_SHORT)
                .show()
        })
    // at last we are adding our request to our queue.
    queue.add(request)
 
}
 
@Composable
fun displayListView() {
    val context = LocalContext.current
   
    // on below line we are creating and
    // initializing our array list
    val courseList = remember { mutableStateListOf<String>() }
    parseJSONArray(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 lstview.
    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:



Last Updated : 28 Jul, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads