What is Retrofit?
Retrofit is a REST Client for Android and Java/Kotlin by Square. It makes it relatively easy to retrieve and upload JSON (or other structured data) via a REST-based web service. In Retrofit, you configure which converter is used for the data serialization.
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 !!