0
0
Android Kotlinmobile~20 mins

Retrofit setup in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Retrofit Setup Screen
This screen sets up Retrofit to fetch data from a sample API and displays a simple message confirming the setup.
Target UI
-------------------------
| Retrofit Setup Screen  |
|-----------------------|
| Status: Not started   |
|                       |
| [Fetch Data]          |
-------------------------
Add Retrofit dependency and setup Retrofit instance
Create a simple API interface with one GET endpoint
Implement a button that triggers a network call using Retrofit
Display the result or error message on the screen
Starter Code
Android Kotlin
package com.example.retrofitsetup

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val statusTextView: TextView = findViewById(R.id.statusTextView)
        val fetchButton: Button = findViewById(R.id.fetchButton)

        fetchButton.setOnClickListener {
            // TODO: Add Retrofit call here
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Solution
Android Kotlin
package com.example.retrofitsetup

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET

class MainActivity : AppCompatActivity() {

    interface ApiService {
        @GET("todos/1")
        fun getTodo(): Call<Todo>
    }

    data class Todo(val userId: Int, val id: Int, val title: String, val completed: Boolean)

    private lateinit var apiService: ApiService

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val statusTextView: TextView = findViewById(R.id.statusTextView)
        val fetchButton: Button = findViewById(R.id.fetchButton)

        val retrofit = Retrofit.Builder()
            .baseUrl("https://jsonplaceholder.typicode.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .build()

        apiService = retrofit.create(ApiService::class.java)

        fetchButton.setOnClickListener {
            statusTextView.text = "Loading..."
            apiService.getTodo().enqueue(object : Callback<Todo> {
                override fun onResponse(call: Call<Todo>, response: Response<Todo>) {
                    if (response.isSuccessful) {
                        val todo = response.body()
                        statusTextView.text = "Title: ${todo?.title ?: "No data"}"
                    } else {
                        statusTextView.text = "Error: ${response.code()}"
                    }
                }

                override fun onFailure(call: Call<Todo>, t: Throwable) {
                    statusTextView.text = "Failure: ${t.message}"
                }
            })
        }
    }
}

This solution sets up Retrofit with a base URL pointing to a sample API. It defines an ApiService interface with a GET request to fetch a todo item. The MainActivity creates a Retrofit instance and the API service. When the user taps the fetch button, it makes an asynchronous network call. The UI updates to show loading, then displays the todo title on success or an error message on failure.

This approach keeps the UI responsive and demonstrates basic Retrofit usage in Android Kotlin.

Final Result
Completed Screen
-------------------------
| Retrofit Setup Screen  |
|-----------------------|
| Status: Title: delectus aut autem |
|                       |
| [Fetch Data]          |
-------------------------
User taps 'Fetch Data' button
Status text changes to 'Loading...'
After network call, status text updates with todo title or error message
Stretch Goal
Add error retry functionality with a Snackbar and a retry button
💡 Hint
Use Snackbar.make() to show error and add an action button that triggers the Retrofit call again