Open In App

How to Update Data in API using Retrofit in Android?

Last Updated : 21 Dec, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

We have seen reading data from API as well as posting data to our database with the help of the API. In this article, we will take a look at updating our data in our API. We will be using the Retrofit library for updating our data in our API. 

What we are going to build in this article? 

We will be building a simple application in which we will be displaying a simple form and with that form, we will be updating our data and passing it to our API to update that data. We will be using PUT request along with the Retrofit library to update our data to API. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java 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 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 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 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"?>
<LinearLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">
  
    <!--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: Creating a modal class for storing our data  

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class and name it as DataModal and add the below code to it. Comments are added in the code to get to know in more detail.  

Java




package com.gtappdevelopers.gfg;
  
public class DataModal {
    // string variables for name and job.
    private String name;
    private String job;
  
    public DataModal(String name, String job) {
        this.name = name;
        this.job = job;
    }
  
    // creating getter and setter methods. 
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getJob() {
        return job;
    }
  
    public void setJob(String job) {
        this.job = job;
    }
}


Step 6: Creating an Interface class for our API Call

Navigate to the app > java > your app’s package name > Right-click on it > New > Java class select it as RetrofitAPI and add below code to it. Comments are added in the code to get to know in more detail.

Java




package com.gtappdevelopers.gfg;
  
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.PUT;
  
public 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")
    
    // on below line we are creating a method to put our data.
    Call<DataModal> updateData(@Body DataModal dataModal);
}


Step 7: Working with MainActivity.java file

Navigate to the app > java > your app’s package name > MainActivity.java file and add the below code to it. Comments are added in the code to get to know in more detail.  

Java




package com.gtappdevelopers.gfg;
  
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
  
import androidx.appcompat.app.AppCompatActivity;
  
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
  
  
public class MainActivity extends AppCompatActivity {
  
    String url = "https://reqres.in/";
      
    // creating our variables for our views such
    // as text view, button and progress 
    // bar and response text view.
    private EditText userNameEdt, jobEdt;
    private Button updateBtn;
    private ProgressBar loadingPB;
    private TextView responseTV;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        // initializing our views with their ids.
        userNameEdt = findViewById(R.id.idEdtUserName);
        jobEdt = findViewById(R.id.idEdtJob);
        updateBtn = findViewById(R.id.idBtnUpdate);
        loadingPB = findViewById(R.id.idPBLoading);
        responseTV = findViewById(R.id.idTVResponse);
          
        // adding on click listener for our button.
        updateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // checking if the edit text is empty or not.
                if (TextUtils.isEmpty(userNameEdt.getText().toString()) && TextUtils.isEmpty(jobEdt.getText().toString())) {
                      
                    // displaying a toast message if the edit text is empty.
                    Toast.makeText(MainActivity.this, "Please enter your data..", Toast.LENGTH_SHORT).show();
                    return;
                }
                  
                // calling a method to update data in our API.
                callPUTDataMethod(userNameEdt.getText().toString(), jobEdt.getText().toString());
            }
        });
    }
  
    private void callPUTDataMethod(String userName, String job) {
        
        // below line is for displaying our progress bar.
        loadingPB.setVisibility(View.VISIBLE);
        
        // on below line we are creating a retrofit
        // builder and passing our base url
        Retrofit retrofit = new 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();
        
        // below the line is to create an instance for our retrofit api class.
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
        
        // passing data from our text fields to our modal class.
        DataModal modal = new DataModal(userName, job);
        
        // calling a method to create an update and passing our modal class.
        Call<DataModal> call = retrofitAPI.updateData(modal);
        
        // on below line we are executing our method.
        call.enqueue(new Callback<DataModal>() {
            @Override
            public void onResponse(Call<DataModal> call, Response<DataModal> response) {
                // this method is called when we get response from our api.
                Toast.makeText(MainActivity.this, "Data updated to API", Toast.LENGTH_SHORT).show();
                
                // below line is for hiding our progress bar.
                loadingPB.setVisibility(View.GONE);
                
                // on below line we are setting empty 
                // text to our both edit text.
                jobEdt.setText("");
                userNameEdt.setText("");
                
                // we are getting a response from our body and 
                // passing it to our modal class.
                DataModal responseFromAPI = response.body();
                
                // on below line we are getting our data from modal class
                // and adding it to our string.
                String responseString = "Response Code : " + response.code() + "\nName : " + responseFromAPI.getName() + "\n" + "Job : " + responseFromAPI.getJob();
                 
                // below line we are setting our string to our text view.
                responseTV.setText(responseString);
            }
  
            @Override
            public void onFailure(Call<DataModal> call, Throwable t) {
                
                // setting text to our text view when
                // we get error response from API.
                responseTV.setText("Error found is : " + t.getMessage());
            }
        });
    }
}


Now run your app and see the output of the app. 

Output:



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads