Skip to content
Related Articles

Related Articles

How to Update Data in API using Retrofit in Android using Jetpack Compose?

View Discussion
Improve Article
Save Article
  • Last Updated : 17 Jul, 2022
View Discussion
Improve Article
Save Article

Android applications use APIs within Android Applications to access data from databases. We can perform several operations using APIs such as Reading, Writing, and Updating our Data in the Database. In this article, we will take a look at How to Update Data in API using Retrofit in Android using Jetpack Compose. 

Note: If you are seeking Java code for Jetpack Compose, please note that Jetpack Compose is only available in Kotlin. It uses features such as coroutines, and the handling of @Composable annotations is handled by a Kotlin compiler. There is no method for Java to access these. Therefore, you cannot use Jetpack Compose if your project does not support 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. 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: Add the below Dependency to 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 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 sync your project and now move towards the AndroidManifest.xml part.

Step 3: Adding Internet Permissions 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 4: Creating a Model Class

Navigate to app > java > your app’s package name > Right-click on it > New > Java/Kotlin class and name your class as DataModel and add the below code to it. Comments are added in the code for further explanation.

Kotlin




data class DataModel(
    // in the below line, we are creating 
      // variables for name and job
    var name: String,
    var job: String
)

Step 5: Creating an Interface Class for API Call

Navigate to the app > java > your app’s package name > Right-click on it > New > Kotlin class select it as RetrofitAPI and add below code to it. Comments are added in the code for further explanation.

Kotlin




import retrofit2.Call
import retrofit2.http.Body
import retrofit2.http.GET
import retrofit2.http.PUT
  
interface RetrofitAPI {
    // as we are making a put request to update a data
    // so we are annotating it with put
    // and along with that we are passing a parameter as users
    @PUT("api/users/2")
    // in the below line, we are creating a method to put our data.
    fun updateData(@Body dataModel: DataModel?): Call<DataModel?>?
}

Step 6: Working with MainActivity.kt file

Navigate to the app > java > your app’s package name > MainActivity.kt file and add the below code to it. Comments are added in the code for further explanation.

Kotlin




import android.app.Activity
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.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.example.newcanaryproject.ui.theme.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.*
  
  
class MainActivity : ComponentActivity() {
  
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            NewCanaryProjectTheme {
                // in the below line, we are specifying background color for our application
                Surface(
                    // in the below line, we are specifying modifier and color for our app
                    modifier = Modifier.fillMaxSize(), color = MaterialTheme.colors.background
                ) {
                    //in the 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(
  
                                        // in the below line, we are specifying text to display in top app bar.
                                        text = "Retrofit PUT Request in Android",
  
                                        // in the below line, we are specifying modifier to fill max width.
                                        modifier = Modifier.fillMaxWidth(),
  
                                        // in the below line, we are specifying text alignment.
                                        textAlign = TextAlign.Center,
  
                                        // in the below line, we are specifying color for our text.
                                        color = Color.White
                                    )
                                })
                        }) {
                        // in the below line, we are calling pop window dialog method to display ui.
                        updateData()
                    }
                }
            }
        }
    }
}
  
@Composable
fun updateData() {
    val ctx = LocalContext.current
  
    val userName = remember {
        mutableStateOf(TextFieldValue())
    }
    val job = remember {
        mutableStateOf(TextFieldValue())
    }
    val response = remember {
        mutableStateOf("")
    }
  
    // in the below line, we are creating a column.
    Column(
        // in the below line, we are adding a modifier to it
        // and setting max size, max height and max width
        modifier = Modifier
            .fillMaxSize()
            .fillMaxHeight()
            .fillMaxWidth(),
  
        // in the below line, we are adding vertical
        // arrangement and horizontal alignment.
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
  
        // in the below line, we are creating a text
        Text(
            // in the below line, we are specifying text as
            // Session Management in Android.
            text = "Retrofit PUT Request in Android",
  
            // in the below line, we are specifying text color.
            color = greenColor,
  
            fontSize = 20.sp,
  
            // in the below line, we are specifying font family
            fontFamily = FontFamily.Default,
  
            // in the below line, we are adding font weight
            // and alignment for our text
            fontWeight = FontWeight.Bold, textAlign = TextAlign.Center
        )
  
        //in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
  
        // in the below line, we are creating a text field for our email.
        TextField(
            // in the below line, we are specifying value for our email text field.
            value = userName.value,
  
            // in the below line, we are adding on value change for text field.
            onValueChange = { userName.value = it },
  
            // in the below line, we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your name") },
  
            // in the below line, we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
  
            // in the below line, we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // in the below line, we ar adding single line to it.
            singleLine = true,
  
            )
  
        // in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(5.dp))
  
        // in the below line, we are creating a text field for our email.
        TextField(
            // in the below line, we are specifying value for our email text field.
            value = job.value,
  
            // in the below line, we are adding on value change for text field.
            onValueChange = { job.value = it },
  
            // in the below line, we are adding place holder as text as "Enter your email"
            placeholder = { Text(text = "Enter your job") },
  
            // in the below line, we are adding modifier to it
            // and adding padding to it and filling max width
            modifier = Modifier
                .padding(16.dp)
                .fillMaxWidth(),
  
            // in the below line, we are adding text style
            // specifying color and font size to it.
            textStyle = TextStyle(color = Color.Black, fontSize = 15.sp),
            // in the below line, we ar adding single line to it.
            singleLine = true,
        )
  
        // in the below line, we are adding spacer
        Spacer(modifier = Modifier.height(10.dp))
  
        // in the below line, we are creating a button
        Button(
            onClick = {
  
                // in the below line, we are calling make payment method to update data.
                updateDataUsingRetrofit(
                    ctx, userName, job, response
                )
            },
            // in the below line, we are adding modifier to our button.
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // in the below line, we are adding text for our button
            Text(text = "Update Data", modifier = Modifier.padding(8.dp))
        }
  
        // in the below line, we are adding a spacer.
        Spacer(modifier = Modifier.height(20.dp))
  
        // in the 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 updateDataUsingRetrofit(
    ctx: Context,
    userName: MutableState<TextFieldValue>,
    job: MutableState<TextFieldValue>,
    result: MutableState<String>
) {
  
    var url = "https://reqres.in/"
  
    // in the below line, we are creating a retrofit
    // builder and passing our base url
    val retrofit = Retrofit.Builder()
        .baseUrl(url)
        // as we are sending data in json format so
        // we have to add Gson converter factory
        .addConverterFactory(GsonConverterFactory.create())
        // at last we are building our retrofit builder.
        .build()
  
    // the below line is creating an instance for our retrofit api class.
    val retrofitAPI = retrofit.create(RetrofitAPI::class.java)
  
    // passing data from our text fields to our model class.
    val dataModel = DataModel(userName.value.text, job.value.text)
  
    // calling a method to create an update and passing our model class.
    val call: Call<DataModel?>? = retrofitAPI.updateData(dataModel)
  
    // in the below line, we are executing our method.
    call!!.enqueue(object : Callback<DataModel?> {
        override fun onResponse(call: Call<DataModel?>?, response: Response<DataModel?>) {
            // this method is called when we get response from our api.
            Toast.makeText(ctx, "Data updated to API", Toast.LENGTH_SHORT).show()
  
            // we are getting a response from our body and
            // passing it to our model class.
            val model: DataModel? = response.body()
  
            // in the below line, we are getting our data from model class
            // and adding it to our string.
            val resp =
                "Response Code : " + response.code() + "\n" + "User Name : " + model!!.name + "\n" + "Job : " + model!!.job
  
            // in the below line, we are setting our string to our response.
            result.value = resp
        }
  
        override fun onFailure(call: Call<DataModel?>?, t: Throwable) {
  
            // we get error response from API.
            result.value = "Error found is : " + t.message
        }
    })
  
}

Now run your application to see the output of it. 

Output:


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!