Retrofit Using Kotlin

Arjun V
3 min readJul 11, 2023

--

Retrofit with Coroutine

In this project, we need a few of the Dependencies for the latest retrofit dependency use https://github.com/square/retrofit. we want a Gson -> Json converter that converts JSON data to Kotlin format Coroutine dependency got from https://github.com/Kotlin/kotlinx.coroutines and Live data and view model add from https://developer.android.com/jetpack/androidx/releases/lifecycle for login intercept implementation(“com.squareup.okhttp3:logginginterceptor:4.11.0”) and kapt dependency and plugin add to build_gradle(Project) file.

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt' //for Annotation processor
}

android {
namespace 'com.posibolt.retrofitdemo'
compileSdk 33

defaultConfig {
applicationId "com.posibolt.retrofitdemo"
minSdk 24
targetSdk 33
versionCode 1
versionName "1.0"

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}

buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
}

dependencies {
implementation 'androidx.core:core-ktx:1.7.0'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation 'com.google.android.material:material:1.9.0'
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
//Retrofit https://square.github.io/retrofit/ - latest vesion https://github.com/square/retrofit.
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
//Gson -> json data to java or kotlin format
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
//coroutines -> https://github.com/Kotlin/kotlinx.coroutines
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.7.2")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.2")
//Viewmodel and livedata -> https://developer.android.com/jetpack/androidx/releases/lifecycle
// ViewModel
implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.6.1")
// LiveData
implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.6.1")
// Annotation processor
kapt("androidx.lifecycle:lifecycle-compiler:2.6.1")
// login intercept
implementation("com.squareup.okhttp3:logging-interceptor:4.11.0")
//jsonplaceholder.typecode.com -> test api
testImplementation 'junit:junit:4.13.2'
androidTestImplementation 'androidx.test.ext:junit:1.1.5'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

2. Test purpose API data we got from jsonplaceholder.typecode.com.

3. Create a Data class based on JSON

AlbumItem.kt :

package com.posibolt.retrofitdemo
import com.google.gson.annotations.SerializedName

data class AlbumItem(
@SerializedName("id")
val id: Int,
@SerializedName("title")
val title: String,
@SerializedName("userId")
val userId: Int
)

Album.kt :

package com.posibolt.retrofitdemo

class Album : ArrayList<AlbumItem>()

4. Mainly Retrofit contains a retrofitInstance class and a service class

RetrofitInstance.kt :

package com.posibolt.retrofitdemo
import com.google.gson.GsonBuilder
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

class RetrofitInstance {

companion object{
val BASE_URL = "https://jsonplaceholder.typicode.com"

fun getRetrofitInstance():Retrofit{
return Retrofit.Builder().baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create(GsonBuilder().create())).build()
}
}
}

Specify your Base URL here..!

AlbumService.kt :

package com.posibolt.retrofitdemo
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query

interface AlbumService {

@GET("/albums")
suspend fun getAlbums(): Response<Album>

}

Here we can specify our method and parameter with the help of a return type function.

5. 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:id="@+id/scrollView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="1dp"
android:layout_marginTop="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="20dp"
android:layout_marginBottom="356dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/scrollView2" />

</ScrollView>

</androidx.constraintlayout.widget.ConstraintLayout>

Textview inside scroll view -> just API data viewing like abow

6. MainActivity.kt

package com.posibolt.retrofitdemo
import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.lifecycle.liveData
import retrofit2.Response

class MainActivity : AppCompatActivity() {
@SuppressLint("MissingInflatedId")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val text_view : TextView = findViewById(R.id.textView)
val retService : AlbumService = RetrofitInstance.getRetrofitInstance().create(AlbumService::class.java)
val responceLiveData : LiveData<Response<Album>> = liveData {
val response: Response<Album> = retService.getAlbums()
emit(response)
}
responceLiveData.observe(this, Observer {
val albumList : MutableListIterator<AlbumItem>? = it.body()?.listIterator()
if(albumList != null){
while (albumList.hasNext()){
val albumItem : AlbumItem = albumList.next()
Log.i("MYTAG",albumItem.title)
val result: String = " "+"Album id : ${albumItem.id}"+"\n"+
" "+"Album title : ${albumItem.title}"+"\n"+
" "+"Album userid : ${albumItem.userId}"+"\n"+"\n"
text_view.append(result)
}
}
})
}
}

--

--