Open In App

Android – Update Data in API using Volley with Kotlin

Improve
Improve
Like Article
Like
Save
Share
Report

Android applications use APIs to get the data from servers in android applications. With the help of APIs, we can add, read, update and delete the data from our database using APIs. We can use Volley and Retrofit for consuming data from APIs within the android application. In this article, we will take a look at How to update data in API using Volley in Android using Kotlin. 

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. Note that select Kotlin as the programming language.

Step 2: Add the below dependency in your build.gradle file

Below is the dependency for Volley which we will be using to get the data from API. For adding this dependency navigate to the app > Gradle Scripts > build.gradle(app) and add the below dependency in the dependencies section.

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

After adding this dependency sync your project and now move towards the AndroidManifest.xml part.  

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 the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<!--on below line we are creating a swipe to refresh layout-->
<LinearLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="true"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!--text view for displaying app name-->
    <TextView
        android:id="@+id/idTVPayment"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10dp"
        android:text="@string/app_name"
        android:textAlignment="center"
        android:textColor="@color/purple_200"
        android:textSize="20sp"
        android:textStyle="bold" />
  
    <!--edit text for our user name-->
    <EditText
        android:id="@+id/idEdtUserName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="10dp"
        android:hint="User Name" />
  
    <!--edit text for our job-->
    <EditText
        android:id="@+id/idEdtJob"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="Job" />
  
    <!--button to update our data-->
    <Button
        android:id="@+id/idBtnUpdate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:text="Update Data"
        android:textAllCaps="false" />
  
    <!--progress bar for the purpose of loading-->
    <ProgressBar
        android:id="@+id/idPBLoading"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:visibility="gone" />
  
    <!--text view to display our 
        response after updating data-->
    <TextView
        android:id="@+id/idTVResponse"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:gravity="center_horizontal"
        android:text="Response"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="15sp" />
    
</LinearLayout>


Step 5: Working with the 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.gtappdevelopers.kotlingfgproject
  
import android.os.Bundle
import android.text.TextUtils
import android.util.Log
import android.view.View
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
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 org.json.JSONException
import org.json.JSONObject
  
class MainActivity : AppCompatActivity() {
  
    // on below line we are creating variables.
    lateinit var nameEdt: EditText
    lateinit var jobEdt: EditText
    lateinit var updateBtn: Button
    lateinit var resultTV: TextView
    lateinit var loadingPB: ProgressBar
    var url = "https://reqres.in/api/users/2"
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
  
        // initializing all our variables.
        nameEdt = findViewById(R.id.idEdtUserName)
        jobEdt = findViewById(R.id.idEdtJob)
        updateBtn = findViewById(R.id.idBtnUpdate)
        resultTV = findViewById(R.id.idTVResponse)
        loadingPB = findViewById(R.id.idPBLoading)
  
        // on below line we are adding 
          // click listener for our update button.
        updateBtn.setOnClickListener {
            // validating user inputs
            if (TextUtils.isEmpty(nameEdt.text) && TextUtils.isEmpty(jobEdt.text)) {
                // on below line we are displaying toast message
                Toast.makeText(this, "Please enter your data..", Toast.LENGTH_SHORT).show()
            }
            addData(nameEdt.text.toString(), jobEdt.text.toString())
        }
    }
  
    private fun addData(userName: String, job: String) {
        // on below line we are displaying our progress bar.
        loadingPB.visibility = View.VISIBLE
  
        // creating a new variable for our request queue
        val queue = Volley.newRequestQueue(this@MainActivity)
  
        // 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?) {
  
                    // hiding our progress bar.
                    loadingPB.visibility = View.GONE
  
                    // inside on response method we are
                    // setting our edit text to empty.
                    jobEdt.setText("")
                    nameEdt.setText("")
  
                    // on below line we are displaying a toast message as data updated.
                    Toast.makeText(this@MainActivity, "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.
                        resultTV.setText(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(this@MainActivity, "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 : 30 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads