Beginner's Guide To Using Retrofit in Android With Kotlin
Beginner's Guide To Using Retrofit in Android With Kotlin
This guide will walk you through the very basics of using Retrofit, a popular networking
library, in your Android applications with Kotlin. We'll use a simple, free online service to get
some dummy data.
1. What is Retrofit?
Imagine your Android app needs to get information from the internet, like a list of products
from an online store, or the weather forecast. Retrofit is a special library that makes it super
easy for your app to talk to these online services (called APIs). It takes care of all the
complicated stuff behind the scenes, so you can focus on what your app needs to do with
the data.
2. What is JSON?
JSON (JavaScript Object Notation) is a way of organizing data so that computers can easily
understand and exchange it. It looks a bit like a dictionary or a set of nested lists. Here's a
very simple example:
JSON
[
{
"id": 1,
"name": "Apple",
"price": 1.00
},
{
"id": 2,
"name": "Banana",
"price": 0.50
}
]
In our guide, we'll get similar JSON data from a dummy provider.
Important: After adding these lines, Android Studio will usually show a message at the top
asking you to "Sync Now". Click on it. This tells Android Studio to download the Retrofit
libraries.
XML
<uses-permission android:name="android.permission.INTERNET"/>
If you open this URL in your web browser, you will see a lot of JSON data like this:
JSON
[
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
},
{
"userId": 1,
"id": 2,
"title": "quis ut nam facilis et officia qui",
"completed": false
}
// ... more items
]
5. Creating Kotlin Data Classes
We need to tell Kotlin how to understand the JSON data we receive. We create a "data
class" that matches the structure of our JSON.
Kotlin
Explanation:
● data class Todo(...): This declares a simple Kotlin class named Todo.
● val userId: Int: This means there will be a piece of data called userId which is a whole
number (Int).
● val id: Int: Similar, for id.
● val title: String: A piece of text (String) called title.
● val completed: Boolean: A true/false value (Boolean) called completed.
Right-click on your package name, then New -> Kotlin Class/File. Name it TodoApiService.kt.
Kotlin
import retrofit2.Call
import retrofit2.http.GET
interface TodoApiService {
@GET("todos") // This is the path relative to our base URL
fun getTodos(): Call<List<Todo>>
}
Explanation:
● interface TodoApiService: We define an interface.
● @GET("todos"): This tells Retrofit that this function will perform a "GET" request
(meaning, it will ask for data) and that the specific part of the URL it should go to is
"todos". Remember our full URL is https://jsonplaceholder.typicode.com/todos.
Retrofit will combine a "base URL" (which we'll define soon) with this "todos" part.
● fun getTodos(): Call<List<Todo>>: This declares a function named getTodos.
○ Call<...>: This is a special Retrofit type that represents a single request to the
web.
○ List<Todo>: This means that when the request is successful, we expect to get
back a List (a collection) of our Todo objects.
Open MainActivity.kt and replace its content with the following (make sure your package
name matches):
Kotlin
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
// Now you have the data! Let's print the first few items to Logcat
todos?.let {
Log.d(TAG, "Successfully fetched ${it.size} todos.")
// Loop through the first 5 todos (or fewer if there aren't 5)
for (i in 0 until minOf(it.size, 5)) {
Log.d(TAG, "Todo ${i+1}: ID=${it[i].id}, Title='${it[i].title}',
Completed=${it[i].completed}")
}
} ?: Log.e(TAG, "Response body is null.")
} else {
// Response was not successful (e.g., 404 Not Found, 500 Server Error)
Log.e(TAG, "Request not successful: ${response.code()}")
}
}
// This function is called if the network request fails (e.g., no internet, server down)
override fun onFailure(call: Call<List<Todo>>, t: Throwable) {
Log.e(TAG, "Network request failed!", t) // Log the error message and the exception
}
})
}
}
Explanation of MainActivity.kt:
1. BASE_URL: This is the unchanging part of the URL for all your API calls.
2. Retrofit.Builder()...build(): This is how you create your main Retrofit object.
○ baseUrl(): Sets the base URL.
○ addConverterFactory(GsonConverterFactory.create()): This is crucial! It tells
Retrofit to use the Gson library to automatically convert the received JSON
into our Todo Kotlin objects.
3. retrofit.create(TodoApiService::class.java): This line creates an actual working
object from our TodoApiService interface. Retrofit uses the definitions in the interface
to build the actual network requests.
4. service.getTodos(): This calls the function we defined in our TodoApiService
interface. It prepares the network request.
5. call.enqueue(...): This is where the magic happens!
○ enqueue means "put this request in line to be done in the background." This
is very important because you should never do network operations directly on
the main screen (UI) thread of your app, as it would make your app freeze.
○ object : Callback<List<Todo>>: We provide an object that follows the Callback
rules. This object has two functions:
■ onResponse(): This function is called when the server sends back a
response, whether it's a successful one or an error response (like
"page not found").
■ response.isSuccessful: Checks if the HTTP status code
indicates success (e.g., 200 OK).
■ response.body(): If successful, this contains our List<Todo>
data!
■ Log.d() and Log.e(): These are used to print messages to the
"Logcat" window in Android Studio. d is for debug, e for error.
This is essential for seeing what's happening.
■ onFailure(): This function is called if something goes wrong with the
network request itself, like no internet connection, or the server being
unreachable.
Once the app starts, it will immediately try to make the network request. You won't see
anything on the screen itself, as we haven't added any UI elements to display the data.
9. Next Steps
Congratulations! You've successfully made your first network request using Retrofit in
Android.