How to use Retrofit Library in Android?


Introduction

Retrofit is one of the famous HTTP libraries which is used to parse the data from the internet using APIS. We can use this library to fetch the data from API in the form of JSON and display that JSON within our application. In this article we will take a look at How to use Retrofit Library in Android.

Implementation

We will be creating a simple application in which we will be creating a text view for displaying the heading of our application. After that we are creating one more text view in which we will be displaying the response from the API call using Retrofit library.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note : Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for heading -->
   <TextView
       android:id="@+id/idTVHeading"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Retrofit in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a response message -->
   <TextView
       android:id="@+id/idTVMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVHeading"
       android:layout_margin="5dp"
       android:padding="4dp"
       android:text="Message"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating one more text view which we are using to display the response from our API call.

Step 3 : Adding permissions in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below permissions to it in manifest tag to read sms.

<!-- adding permissions on below line -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Step 4 : Adding dependency for using Retrofit library in build.gradle file

Navigate to Gradle Scripts> build.gradle file and in the dependencies section add below dependencies to use the retrofit library.

// adding below dependencies.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'

After adding the above dependencies in the dependencies section. Simply sync your project to install all the dependencies.

Step 5 : Creating a new java class for Response Object

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

package com.example.java_test_application;
// on below line creating a class for response object.
public class ResponseObject {
   // on below line creating a variable for message.
   private String message;
   // on below line creating a getter method.
   public String getMessage() {
       return message;
   }
   // on below line creating a setter method.
   public void setMessage(String message) {
       this.message = message;
   }
   // on below line creating a constructor method.l
   public ResponseObject(String message) {
       this.message = message;
   }
}

Step 6 : Creating an interface class for making a retrofit API call

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

package com.example.java_test_application;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitAPICall {
   // as we are making a get request specifying annotation as get and adding a url end point to it.
   @GET("43d590f03930")
   // on below line specifying the method name which we have to call.
   Call<ResponseObject> getData();
}

Step 7 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.java_test_application;
import android.os.Bundle;
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 {
   // creating variables for text view on below line.
   private TextView msgTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      //initializing variable for text view and button on below line.
      msgTV = findViewById(R.id.idTVMsg);
      // on below line we are creating a retrofit
      // builder and passing our base url
      Retrofit retrofit = new Retrofit.Builder().baseUrl("https://json.extendsclass.com/bin/")
         // on below line we are calling add Converter
         // factory as GSON converter factory.
         .addConverterFactory(GsonConverterFactory.create())
         // at last we are building our retrofit builder.
         .build();
      // below line is to create an instance for our retrofit api call class and initializing it.
      RetrofitAPICall retrofitAPI = retrofit.create(RetrofitAPICall.class);
      // on below line creating and initializing call variable for get data method.
      Call<ResponseObject> call = retrofitAPI.getData();
      // on below line adding an enqueue to parse the data from api.
      call.enqueue(new Callback<ResponseObject>() {
         // on below line calling on response method.
         @Override
         public void onResponse(Call<ResponseObject> call, Response<ResponseObject> response) {
            // inside on response method setting text from our api response.
            msgTV.setText(response.body().getMessage());
         }
         // on below line calling on failure method.
         @Override
         public void onFailure(Call<ResponseObject> call, Throwable t) {
            // displaying a toast message when as error is received.
            Toast.makeText(MainActivity.this, "Fail to get the data..", Toast.LENGTH_SHORT).show();
         }
      });
   }
}

Explanation : In the above code firstly we are creating variable for our text view. Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file. Inside the onCreate method we are initializing the variables for the text view. Then we are creating and initializing the variable for Retrofit. Inside this we are also specifying the base url and adding a gson converter factory to it. After that we are making a retrofit api call by using call.enqueue method. Inside this method we are creating two methods on response and on failure. Inside the response method we are setting the text message to our text view and on the error method we are displaying a toast message.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note : Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above article we have taken a look at How to use Retrofit library in Android and how we can use this library to load the data from the internet.

Updated on: 09-May-2023

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements