Simple Retrofit in Android Kotlin.

Harshita Bambure
2 min readNov 14, 2021

--

Mostly we use retrofit with MVVM or MVP now we will learn how to use simple retrofit in android kotlin.

First of all, we will add internet permission in the manifest file.

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

After that, we need to add some dependencies to the build.Gradle(:app) file.

implementation 'com.google.code.gson:gson:2.8.9'
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

implementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.1'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.5.2-native-mt'
implementation 'androidx.lifecycle:lifecycle-runtime-ktx:2.4.0'

Now we will create models from JSON files. For creating models I am using https://reqres.in/ website for API response.

ResponseListUsers.kt

data class ResponseListUsers(
@SerializedName("data")
var data: List<Data>,
@SerializedName("page")
var page: Int,
@SerializedName("per_page")
var perPage: Int,
@SerializedName("support")
var support: Support,
@SerializedName("total")
var total: Int,
@SerializedName(
"total_pages")
var totalPages: Int
)

Data. kt

data class Data(
@SerializedName("avatar")
var avatar: String,
@SerializedName("email")
var email: String,
@SerializedName("first_name")
var firstName: String,
@SerializedName("id")
var id: Int,
@SerializedName("last_name")
var lastName: String,
//var suport:Support
)

Support. kt

data class Support(
@SerializedName("text")
var text: String,
@SerializedName("url")
var url: String
)

Now we will create a retrofit class.

RetrofitClient.kt

object RetrofitClient {

fun getInstance(): Retrofit {
var mHttpLoggingInterceptor = HttpLoggingInterceptor()
.setLevel(HttpLoggingInterceptor.Level.BODY)

var mOkHttpClient = OkHttpClient
.Builder()
.addInterceptor(mHttpLoggingInterceptor)
.build()


var retrofit: Retrofit = retrofit2.Retrofit.Builder()
.baseUrl("https://reqres.in")
.addConverterFactory(GsonConverterFactory.create())
.client(mOkHttpClient)
.build()
return retrofit
}

}

Now we will create the API Interface class.

ApiInterface.kt

interface ApiInterface {
@GET("/api/users?page=2")
suspend fun getAllUsers(): Response<ResponseListUsers>
}

Now we will add a text view in the layout file.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ScrollView

android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">

<TextView
android:id="@+id/txtData"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Hello World!" />
</ScrollView>


</androidx.constraintlayout.widget.ConstraintLayout>

now we will add the below code in the main activity.

MainActivity.kt

package com.example.myapplication

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.example.myapplication.api.ApiInterface
import com.example.myapplication.api.RetrofitClient
import com.example.myapplication.models.ResponseListUsers
import com.google.gson.Gson
import java.lang.Exception

class MainActivity : AppCompatActivity() {

lateinit var txtData: TextView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
txtData = findViewById(R.id.txtData)
getUserList()
}

fun getUserList() {
var retrofit = RetrofitClient.getInstance()
var apiInterface = retrofit.create(ApiInterface::class.java)
lifecycleScope.launchWhenCreated {
try {
val response = apiInterface.getAllUsers()
if (response.isSuccessful()) {
//your code for handaling success response


} else {
Toast.makeText(
this@MainActivity,
response.errorBody().toString(),
Toast.LENGTH_LONG
).show()
}
}catch (Ex:Exception){
Log.e("Error",Ex.localizedMessage)
}
}

}

}

Here is the source code.

Thank You for Reading. Happy Coding :)

--

--

Harshita Bambure

Android Developer || WomenTech Global Ambassador at WomenTech Network. || Yoga Teacher || Member @WTM .