How To Use Retrofit Tutorial in Kotlin
What is Retrofit?
Ohh! Such a tough definition
Let us simplify this – As an Android developer at one time you want your app to communicate with the internet, i.e receive something or send something to the internet. So to make this communication to send or receive data on the Internet we use Retrofit.
So Retrofit makes it easier to communicate with the Internet and it sends and receives data in JSON (JavaScript Object Notation)
Prerequisite
We are considering that you have basic knowledge of android and Kotlin and that’s Enough.
So Much Theory…
Retrofit Tutorial in Kotlin [Complete Code]
We will be building an Android app to display a list of superheroes in our App. Here is an example
Before getting started we should know that we make mainly four types of request on RESTful API.
- GET Request ( For Receiving data )
- POST Request ( For Sending data )
- PUT Request ( For Updating data )
- DELETE Request ( For Deleting data )
In this example, we will be using the Get request.
We will be using this API
https://simplifiedcoding.net/demos/marvel/
Creating a new Project
- Let’s first create a new Android Studio Project. I have created a project named RetrofitExample.
- Once the project is created we need to add the following two libraries to our project.
- Retrofit -> For the network calls
- Gson -> For easy parsing of JSON data
// Firstly add these dependencies change these according to the latest version
dependencies {
...
// Retrofit
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
// GSON
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
}
We also need Internet Permission so we will declare that in Manifest File.
<uses-permission android:name="android.permission.INTERNET" />
In Retrofit we use annotation or ‘@’ Symbol to denote the type of request
Create a new Kotlin Interface file of name superheroAPI
interface superheroAPI {
@GET("marvel") // making get request at marvel end-point
fun getHeroes(): Call<List<Heros?>?>?
}
In the above code, we are making a GET request to the API and the “marvel” is the End-Point.
Read More: Google Login And Registration For Android Using Firebase Authentication
Then we are declaring a function getHeroes() which will return a List of Hero.
We will face an error because we have not declared our Heros data class, So let’s make it.
// Create a new Kotlin data class of name Heros
data class Heros(var name: String, var realname: String, var team: String, var firstappearance: String, var createdby: String, var publisher: String, var imageurl: String, var bio: String)
Make sure your variable names match the JSON attributes. As we have the following JSON objects in our response.
{
name: "Captain America",
realname: "Steve Rogers",
team: "Avengers",
firstappearance: "1941",
createdby: "Joe Simon",
publisher: "Marvel Comics",
imageurl: "https://www.simplifiedcoding.net/demos/marvel/captainamerica.jpg",
bio: " Steven Rogers was born in the Lower East Side..... "
}
We can see that the data class contain the same name as of the API.
Now we will make the API call
In activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="com.jayant.Retrofit.MainActivity">
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
In MainActivity.kt
// Explaination below
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_dashboard){
var retrofit = Retrofit.Builder()
.baseUrl("https://simplifiedcoding.net/demos/")
.addConverterFactory(GsonConverterFactory.create())
.build(); // Part 1
val api = retrofit.create(superheroAPI::class.java); //Part 2
api.getHeroes().enqueue(object : Callback<List<Hero?>?>() {
fun onResponse(call: Call<List<Hero?>?>?,
response: Response<List<Hero?>?>) {
val heroList: List<Hero> = response.body() // Now we can use
this heroList for getting the data from API.
//Creating an String array for the ListView
val heroes = arrayOfNulls<String>(heroList.size)
//looping through all the heroes and inserting the names
inside the string array
for (i in heroList.indices) {
heroes[i] = heroList[i].name
}
//displaying the string array into listview
listView.setAdapter(
ArrayAdapter(
applicationContext,
android.R.layout.simple_list_item_1,
heroes
)
) //Part Extra
}
fun onFailure(call: Call<List<Hero?>?>?, t: Throwable) {
Toast.makeText(applicationContext, t.message,
Toast.LENGTH_SHORT).show()
}
}) //Part 3
}
}
Explaination of different Parts of MainActivity.kt
Part 1
- We are creating an instance of the Retrofit Builder class.
- Then we are adding the base URL i.e. “https://simplifiedcoding.net/demos/”.
- Then adding the converter factory as a Gson converter factory( It converts Java/kotlin objects to JSON and vice versa).
- And at last, we are calling the build method.
Part 2
We are calling the create method for the interface that we created earlier.
Part 3
- Firstly we are calling the getHeros() function from the interface
- Then calling the enqueue function which will override two methods – onResponse and onFailure
- In onResponse, we will write up for the response using the ‘response.body()’ method
- In onFailure, we will handle up for any failure like – There is no Internet.
Part Extra
We are showing the response in form of a list so we are creating an adapter for the list.
And That’s all Folks !!
Jayant dhingra
As an enthusiast of stock markets and a skilled developer specializing in Android and augmented reality technologies, I am constantly driven to experiment with code.
Related Posts
7 Top Samsung Galaxy Ring Alternatives for 2025
Tired of waiting for the Samsung Galaxy Ring to hit the market? You’re not alone. The smart ring market already has many impressive alternatives available now, despite the buzz around Samsung’s upcoming smart ring. These devices pack advanced health tracking and contactless payment features that might surpass Samsung’s planned offerings. The current lineup of smart […]
What Is Quiet Mode on Instagram and How to Activate It
Ever wondered what Quiet Mode on Instagram is all about? This simple yet powerful Instagram feature helps you take a break from the constant buzz of notifications and focus on what truly matters. Whether you’re striving for better work-life balance, dedicating time to studying, or simply trying to disconnect from social media distractions, Quiet Mode […]
How to Make a Bed in Minecraft (Step-by-Step Guide)
A bed in Minecraft is very important. It lets you skip the night and set your spawn point, so if you die, you will return to your bed instead of the original world spawn. This guide will show you how to gather materials, craft a bed, and set your spawn point. We’ll also show you how to customize your bed, build bunk […]
10 Best MMORPG Games For Android
Not too long ago, MMORPG games and powerful gaming consoles were mostly exclusive to PCs. They required high-end graphics and systems to deliver their immersive gameplay. But times have changed. With the rise of gaming-oriented smartphones, you can now enjoy PC-like gaming experiences on your Android device. Thanks to these technological advancements and faster internet […]
Roblox: Fruit Battlegrounds codes (January 2025)
Fruit Battlegrounds codes are all about getting more gems and help you to shoot up your rank in this One Piece anime-inspired game. This Fruit Battlegrounds was made by Popo developer. It is an action-packed game where players battle it out using unique fruit-based abilities. With constant updates, new fruits, and exciting challenges, it’s a fruity frenzy you won’t […]
Roblox: Ultimate Football Codes (January 2025)
Want to get some extra items for Ultimate Football in Roblox? You’ve come to the right place! Here’s the latest list of codes to help you score touchdowns and look stylish on the field. These codes offer free rewards such as coins and cosmetics to enhance your gameplay. What are Ultimate Football Codes? Ultimate Football […]
Roblox: Da Hood Codes (January 2025)
Are you a fan of Roblox games, in this article we will look at the Roblox Da Hood Codes for December 2024 that will help you unlock exclusive items, improve your gameplay and dominate the streets of Da Hood. You can feel that the game is inspired by the Grand Theft Auto series and there […]