Open In App

Android – Update Data in API Using Volley with Jetpack Compose

Improve
Improve
Like Article
Like
Save
Share
Report

APIs are used in android applications to access data from servers. We can perform various CRUD operations using these APIs within our database such as adding new data, updating data, and reading as well as updating data. In this article, we will take a look at How to Update Data in API using Volley in Android 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 in build.gradle

Navigate to build.gradle and add the below dependency to it in the dependencies section. 

// below line is used for volley library
implementation ‘com.android.volley:volley:1.1.1’

After adding the dependency simply sync your project to install it. 

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 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.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
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.text.TextStyle
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.*
import com.android.volley.Request
import com.android.volley.Response
import com.android.volley.VolleyError
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.example.newcanaryproject.ui.theme.*
import org.json.JSONException
import org.json.JSONObject
import java.util.*
 
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 = "Volley PUT Request 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.
                        updateDataUsingVolley()
                    }
                }
            }
        }
    }
}
 
@Composable
fun updateDataUsingVolley() {
    // on below line we are creating a
    // variable for our context
    val ctx = LocalContext.current
 
    // on below line we are creating variables
    // for user name, job and response.
    val userName = remember {
        mutableStateOf(TextFieldValue())
    }
    val job = remember {
        mutableStateOf(TextFieldValue())
    }
    val response = remember {
        mutableStateOf("")
    }
 
    // on the below line we are creating a column.
    Column(
        // on below line we are adding a modifier to it
        // and setting max size, max height and max width
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth(),
 
        // on below line we are adding vertical
        // arrangement and horizontal alignment.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
 
        // on below line we are creating a text
        Text(
            // on below line we are specifying text as
            // Session Management in Android.
            text = "Volley PUT Request in Android",
 
            // on below line we are specifying text color.
            color = greenColor,
 
            fontSize = 20.sp,
 
            // on below line we are specifying font family
            fontFamily = FontFamily.Default,
 
            // on below line we are adding font weight
            // and alignment for our text
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = userName.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { userName.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your name") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
             
              // on below line we are adding
              // single line to it.
            singleLine = true,
 
            )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
 
        // on below line we are creating
        // a text field for our email.
        TextField(
            // on below line we are specifying
            // value for our email text field.
            value = job.value,
 
            // on below line we are adding on
            // value change for text field.
            onValueChange = { job.value = it },
 
            // on below line we are adding place holder
            // as text as "Enter your email"
            placeholder = { Text(text = "Enter your job") },
 
            // on below line we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
 
            // on below line we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
             
              // on below line we are adding
              // single line to it.
            singleLine = true,
        )
 
        // on below line we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
 
        // on below line we are creating a button
        Button(
            onClick = {
                // on below line we are calling make
                // payment method to update data.
                updateData(
                    userName.value.text, job.value.text, ctx, response
                )
            },
            // on below line we are adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // on below line we are adding text for our button
            Text(text = "Update Data", modifier = Modifier.padding(8.dp))
        }
 
        // on below line we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
 
        // on below line we are creating a
        // text for displaying a response.
        Text(
            text = response.value,
            color = Color.Black,
            fontSize = 20.sp,
            fontWeight = FontWeight.Bold, modifier = Modifier
                .padding(10.dp)
                .fillMaxWidth(),
            textAlign = TextAlign.Center
        )
    }
}
 
 
private fun updateData(
    userName: String,
    job: String,
    ctx: Context,
    res: MutableState<String>
) {
    // on below line we are creating a variable for url.
    val url = "https://reqres.in/api/users/2"
 
    // creating a new variable for our request queue
    val queue = Volley.newRequestQueue(ctx)
 
    // making a string request to update our data and
    // passing method as PUT. to update our data.
    val request: StringRequest =
        object : StringRequest(Request.Method.PUT, url, object : Response.Listener<String?> {
            override fun onResponse(response: String?) {
 
                // on below line we are displaying a toast message as data updated.
                Toast.makeText(ctx, "Data Updated..", Toast.LENGTH_SHORT).show()
                try {
                    // on below line we are extracting data from our json object
                    // and passing our response to our json object.
                    val jsonObject = JSONObject(response)
 
                    // creating a string for our output.
                    val result =
                        "User Name : " + jsonObject.getString("name") + "\n" + "Job : " + jsonObject.getString(
                            "job"
                        ) + "\n" + "Updated At : " + jsonObject.getString("updatedAt")
 
                    // on below line we are setting
                    // our string to our text view.
                    res.value = result
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }
        }, object : Response.ErrorListener {
            override fun onErrorResponse(error: VolleyError?) {
                // displaying toast message on response failure.
                Log.e("tag", "error is " + error!!.message)
                Toast.makeText(ctx, "Fail to update data..", Toast.LENGTH_SHORT)
                    .show()
            }
        }) {
            override fun getParams(): Map<String, String>? {
 
                // below line we are creating a map for storing
                // our values in key and value pair.
                val params: MutableMap<String, String> = HashMap()
 
                // on below line we are passing our key
                // and value pair to our parameters.
                params["name"] = userName
                params["job"] = job
 
                // at last we are
                // returning our params.
                return params
            }
        }
    // below line is to make
    // a json object request.
    queue.add(request)
}


Now run your application to see the output of it. 

Output:



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