Retrofit with Kotlin in Android

Recent Posts

Derived Web

Kotlin In Android


Kotlin In Android

Retrofit is a type-safe http client which is used to retrieve, update and delete the data from web services. Nowadays retrofit libraries are popular among the developers to use the API key. The Kotlin team defines it as “lightweight threads”. They are sort of tasks that the actual threads can execute. Coroutines were added to Kotlin in version 1.3 and are based on established concepts from other languages. Kotlin introduced a new style of concurrency that can be used on Android to simplify async code. In this article, we will learn about retrofit using Kotlin coroutine. So we will be using Retrofit for network requests. Retrofit is a very popular library used for working APIs and very commonly used as well. We will learn it by making a simple app using an API to get some data using Retrofit.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in Android Studio

Step 2: Add dependency

Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section.

We are using GSON to convert JSON to kotlin(Java) objects. We will add these dependencies in the build.gradle file inside our project.

Step 3: We will use the below API

So our JSON response will look like this.

Step 4: Then we will create data classes according to JSON response

In JSON response we have 2 JSON objects, So we will create 2 data class

QuoteList and Results

2nd data class

Step 5:

We will create a Retrofit interface to add the endpoints of the URL (quotes in our case is the endpoint)

Step 6:

We will create a new file to get the Retrofit object

In this file, we will have a function that will return the Retrofit object.

Step 7:

Now we will link the Retrofit object and Retrofit interface file in MainActivity

Step 8:

Add Internet permission in the manifests file

< uses-permission android:name=”android.permission.INTERNET”>< /uses-permission>

Results: we can check the logcat window. We can see the result in the green box.