Open In App

Android – JSON Parsing using Volley Library with Jetpack Compose

Last Updated : 29 Jul, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 implementation of JsonObject using Volley in Android using Jetpack Compose. We will be creating a simple application in which we will be parsing the data from a URL using the Volley library in Android using 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. Comments are added to the code. 

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

// dependency for loading image from url
implementation("io.coil-kt:coil-compose:2.0.0-rc01")

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.content.Intent
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import coil.compose.rememberAsyncImagePainter
import com.android.volley.Request
import com.android.volley.RequestQueue
import com.android.volley.toolbox.JsonObjectRequest
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 calling pop window
                        // dialog method to display ui.
                        volleyJSONParsing()
                    }
                }
            }
        }
    }
}
 
// on below line we are creating
// a pop up window dialog method
@Composable
fun volleyJSONParsing() {
    val ctx = LocalContext.current
    // on below line we are creating variables.
    val courseName = remember {
        mutableStateOf("")
    }
    val courseRequisites = remember {
        mutableStateOf("")
    }
    val courseImg = remember {
        mutableStateOf("")
    }
    val courseDesc = remember {
        mutableStateOf("")
    }
    val courseLink = remember {
        mutableStateOf("")
    }
    val progress = remember {
        mutableStateOf(true)
    }
 
    jsonParsing(ctx, courseName, courseRequisites, courseImg, courseDesc, courseLink, progress)
 
    // on the below line we are creating a column.
    Column(
        // in this column we are specifying
        // modifier to add padding and fill
        // max size
        modifier = Modifier
            .fillMaxSize()
            .padding(horizontal = 20.dp),
 
        // on below line we are adding horizontal alignment
        // and vertical arrangement
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Top
    ) {
 
        // on below line we are creating a column.
        if (progress.value) {
            Column(
                // in this column we are specifying
                // modifier to add padding and fill
                // max size
                modifier = Modifier
                    .fillMaxSize()
                    .padding(horizontal = 20.dp),
 
                // on below line we are adding horizontal alignment
                // and vertical arrangement
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                // below line is use to display a circular progress bar.
                CircularProgressIndicator(
                    // below line is use to add padding
                    // to our progress bar.
                    modifier = Modifier.padding(16.dp),
                    // below line is use to add color to our progress bar.
                    color = colorResource(id = R.color.purple_200),
                    // below line is use to add stroke
                    // width to our progress bar.
                    strokeWidth = Dp(value = 4F)
                )
            }
        }
 
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(4.dp))
 
        // on below line we are adding image for our image view.
        Image(
            // on below line we are adding the image url
            // from which we will  be loading our image.
            painter = rememberAsyncImagePainter(courseImg.value),
 
            // on below line we are adding content
            // description for our image.
            contentDescription = "gfg image",
 
            // on below line we are adding modifier for our
            // image as wrap content for height and width.
            modifier = Modifier
                .wrapContentSize()
                .wrapContentHeight()
                .fillMaxWidth()
                .padding(4.dp),
            alignment = Alignment.Center
        )
 
        // on the below line we are adding a spacer.
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line we are creating
        // text for course name.
        Text(
            text = courseName.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 20.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are adding
        // text for course prerequisites
        Text(
            text = courseRequisites.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 16.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Normal, textAlign = TextAlign.Center
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(30.dp))
 
        // on below line we are creating a
        // text for our description.
        Text(
            text = courseDesc.value,
            modifier = Modifier.fillMaxWidth(),
            color = Color.Black,
            fontSize = 15.sp,
            fontFamily = FontFamily.Default,
            fontWeight = FontWeight.Normal, textAlign = TextAlign.Start
        )
 
        // on the below line we are creating a column.
        Column(
            // in this column we are specifying
            // modifier to add padding and fill
            // max size
            modifier = Modifier.fillMaxSize(),
            // on below line we are adding horizontal alignment
            // and vertical arrangement
            horizontalAlignment = Alignment.CenterHorizontally,
            verticalArrangement = Arrangement.Bottom
        ) {
            // on below line we are creating a button
            Button(
                onClick = {
                    // on below line we are opening
                    // a intent to view the url.
                    val i = Intent(Intent.ACTION_VIEW)
                    i.setData(Uri.parse(courseLink.value))
                    ctx.startActivity(i)
                },
                // on below line we are
                // adding modifier for our button.
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(3.dp)
                    .align(Alignment.CenterHorizontally)
                    .fillMaxWidth()
            ) {
                // on below line we are setting text as visit course
                Text(text = "Visit Course", color = Color.White)
            }
 
        }
 
    }
}
 
 
fun jsonParsing(
    ctx: Context,
    name: MutableState<String>,
    requisites: MutableState<String>,
    Img: MutableState<String>,
    Desc: MutableState<String>,
    Link: MutableState<String>,
    progress: MutableState<Boolean>,
) {
 
    // on below line we are creating
    // a variable for our url.
    var url = "https://jsonkeeper.com/b/8RFY"
 
    // on below line we are creating a variable for
    // our request queue and initializing it.
    val queue: RequestQueue = Volley.newRequestQueue(ctx)
 
    // on below line we are creating a variable for request
    // and initializing it with json object request
    val request = JsonObjectRequest(Request.Method.GET, url, null, { response ->
 
        // this method is called when we get a successful response from API.
 
        // on below line we are adding a try catch block.
        try {
            // on below line we are getting data from our response
            // and setting it in variables.
            val courseName: String = response.getString("courseName")
            val courseLink: String = response.getString("courseLink")
            val courseImg: String = response.getString("courseimg")
            val courseDesc: String = response.getString("courseDesc")
            val coursePreq: String = response.getString("Prerequisites")
 
            // on below line we are setting
            // data to our variables which we have passed.
            name.value = courseName
            Link.value = courseLink
            requisites.value = coursePreq
            Img.value = courseImg
            Desc.value = courseDesc
            progress.value = false
 
        } catch (e: Exception) {
            // on below line we are
            // handling our exception.
            e.printStackTrace()
        }
 
    }, { error ->
        // this method is called when we get any error while
        // fetching data from our API
        // 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)
}


Now run your application to see the output of it.

Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads