0% found this document useful (0 votes)
18 views7 pages

Beginner's Guide To Using Retrofit in Android With Kotlin

This guide provides a beginner-friendly introduction to using Retrofit, a networking library for Android applications with Kotlin, focusing on fetching JSON data from an online service. It covers setting up a project, adding necessary dependencies, creating data classes, defining a Retrofit interface, and making network requests. The guide concludes with suggestions for further exploration, such as displaying data in the UI and handling different types of HTTP requests.

Uploaded by

kaushal_theguru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views7 pages

Beginner's Guide To Using Retrofit in Android With Kotlin

This guide provides a beginner-friendly introduction to using Retrofit, a networking library for Android applications with Kotlin, focusing on fetching JSON data from an online service. It covers setting up a project, adding necessary dependencies, creating data classes, defining a Retrofit interface, and making network requests. The guide concludes with suggestions for further exploration, such as displaying data in the UI and handling different types of HTTP requests.

Uploaded by

kaushal_theguru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

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.

3. Setting Up Your Android Project


First, open Android Studio and create a new project. Choose "Empty Activity" as your
template.

3.1 Adding Retrofit to Your Project (Dependencies)


To use Retrofit, you need to tell your project about it. Open the build.gradle (Module :app) file
in your project. You'll find a section called dependencies { ... }. Add the following lines inside
this section:
Gradle

// For Retrofit itself


implementation 'com.squareup.retrofit2:retrofit:2.9.0'
// For converting JSON to Kotlin objects (using Gson)
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'

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.

3.2 Adding Internet Permission


Your app needs permission to access the internet. Open the AndroidManifest.xml file. Just
inside the <manifest> tag and before the <application> tag, add this line:

XML

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

4. Our Dummy JSON Data Provider


We will use JSONPlaceholder as our dummy data provider. It provides fake API data for
testing. Specifically, we'll fetch a list of "todos" (simple tasks).

The URL for our data will be: https://jsonplaceholder.typicode.com/todos

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.

Right-click on your package name (e.g., com.example.myretrofitapp) in the Project panel,


then choose New -> Kotlin Class/File. Name it Todo.kt.

Inside Todo.kt, add the following code:

Kotlin

package com.example.myretrofitapp // Your package name might be different

data class Todo(


val userId: Int,
val id: Int,
val title: String,
val completed: Boolean
)

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.

6. Creating a Retrofit Interface


Now, we define a Kotlin interface that tells Retrofit how to make the web request.

Right-click on your package name, then New -> Kotlin Class/File. Name it TodoApiService.kt.

Inside TodoApiService.kt, add the following code:

Kotlin

package com.example.myretrofitapp // Your package name might be different

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.

7. Making the Network Request in Your Activity


Finally, let's put it all together in your MainActivity.kt file.

Open MainActivity.kt and replace its content with the following (make sure your package
name matches):

Kotlin

package com.example.myretrofitapp // Your package name might be different

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

class MainActivity : AppCompatActivity() {

// A tag for logging messages, makes it easy to filter in Logcat


private val TAG = "RetrofitExample"

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main) // Your layout file

// 1. Define the Base URL for our API


// This is the common part of all your API requests
val BASE_URL = "https://jsonplaceholder.typicode.com/"
// 2. Create a Retrofit instance
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL) // Set the base URL
.addConverterFactory(GsonConverterFactory.create()) // Tell Retrofit to use Gson for
JSON conversion
.build() // Build the Retrofit object

// 3. Create an instance of our API service interface


val service = retrofit.create(TodoApiService::class.java)

// 4. Make the network request


// Call the getTodos() function defined in our TodoApiService
val call = service.getTodos()

// 5. Enqueue the request (make it happen in the background)


call.enqueue(object : Callback<List<Todo>> {
// This object will handle the result of the network request

// This function is called if the network request is successful


override fun onResponse(call: Call<List<Todo>>, response: Response<List<Todo>>) {
if (response.isSuccessful) { // Check if the response was successful (e.g., status code
200)
val todos = response.body() // Get the list of Todo objects

// 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.

8. Running Your App and Checking Logcat


1.​ Connect your Android device or start an emulator in Android Studio.
2.​ Click the "Run 'app'" button (the green triangle) in Android Studio.

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.

To see the results:


1.​ Open the Logcat window at the bottom of Android Studio (if it's not already open).
2.​ In the search bar of Logcat, type RetrofitExample (this is the TAG we defined).
3.​ You should see messages like these if everything worked correctly:
D RetrofitExample: Successfully fetched 200 todos.
D RetrofitExample: Todo 1: ID=1, Title='delectus aut autem', Completed=false
D RetrofitExample: Todo 2: ID=2, Title='quis ut nam facilis et officia qui', Completed=false
...
4.​
5.​ If you see error messages, carefully re-check all the steps, especially the
dependencies, internet permission, and the URLs.

9. Next Steps
Congratulations! You've successfully made your first network request using Retrofit in
Android.

Here are some things you can explore next:


●​ Displaying Data on UI: Instead of just logging, try to display the Todo items in a
TextView or a RecyclerView on your app's screen.
●​ Error Handling: Learn more about different HTTP error codes and how to handle
them gracefully.
●​ POST, PUT, DELETE: Explore other types of HTTP requests using @POST, @PUT,
and @DELETE annotations in your Retrofit interface to send data to the server,
update it, or delete it.
●​ Query Parameters and Path Parameters: Learn how to send additional information
with your requests.
●​ Asynchronous vs. Synchronous: Understand the difference between enqueue
(asynchronous, recommended) and execute (synchronous, to be avoided on the
main thread).
●​ Coroutines: For more advanced asynchronous programming, you can integrate
Retrofit with Kotlin Coroutines.

You might also like