Bird
Raised Fist0
Android Kotlinmobile~20 mins

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

Choose your learning style10 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

Practice

(1/5)
1. What is the main purpose of Retrofit in Android Kotlin development?
easy
A. To manage local databases
B. To simplify network calls and convert web data into Kotlin objects
C. To create user interfaces easily
D. To handle app navigation between screens

Solution

  1. Step 1: Understand Retrofit's role

    Retrofit is a library designed to make network calls easier and convert JSON or XML responses into Kotlin objects automatically.
  2. Step 2: Compare with other options

    Options A, B, and D relate to UI, databases, and navigation, which are not Retrofit's purpose.
  3. Final Answer:

    To simplify network calls and convert web data into Kotlin objects -> Option B
  4. Quick Check:

    Retrofit = Network calls + data conversion [OK]
Hint: Retrofit = network calls + data conversion [OK]
Common Mistakes:
  • Confusing Retrofit with UI or database libraries
  • Thinking Retrofit manages navigation
  • Assuming Retrofit is for local storage
2. Which of the following is the correct way to start building a Retrofit instance in Kotlin?
easy
A. val retrofit = Retrofit.newInstance("https://api.example.com")
B. val retrofit = Retrofit.create().baseUrl("https://api.example.com")
C. val retrofit = Retrofit.Builder().baseUrl("https://api.example.com").build()
D. val retrofit = Retrofit.Builder().create("https://api.example.com")

Solution

  1. Step 1: Recall Retrofit Builder syntax

    The correct way is to use Retrofit.Builder(), set the baseUrl, and then call build() to create the instance.
  2. Step 2: Check each option

    val retrofit = Retrofit.Builder().baseUrl("https://api.example.com").build() uses the correct Builder pattern. Options A, B, and C use incorrect methods or order.
  3. Final Answer:

    val retrofit = Retrofit.Builder().baseUrl("https://api.example.com").build() -> Option C
  4. Quick Check:

    Builder + baseUrl + build() = correct setup [OK]
Hint: Use Builder, set baseUrl, then build() [OK]
Common Mistakes:
  • Calling create() before build()
  • Using newInstance() which doesn't exist
  • Passing URL to create() instead of baseUrl()
3. Given this Retrofit setup code snippet, what will be the output if you call service.getUsers() and the server returns JSON data?
val retrofit = Retrofit.Builder()
  .baseUrl("https://api.example.com/")
  .addConverterFactory(GsonConverterFactory.create())
  .build()

interface ApiService {
  @GET("users")
  suspend fun getUsers(): List<User>
}

val service = retrofit.create(ApiService::class.java)
medium
A. A raw JSON string from the server
B. A null value because the call is not executed
C. An error because GsonConverterFactory is missing
D. A List of User objects parsed from the JSON response

Solution

  1. Step 1: Understand the converter role

    GsonConverterFactory converts JSON responses into Kotlin objects automatically.
  2. Step 2: Analyze the service call

    Calling getUsers() returns a List<User> parsed from JSON because of the converter and suspend function.
  3. Final Answer:

    A List of User objects parsed from the JSON response -> Option D
  4. Quick Check:

    GsonConverterFactory + suspend fun = parsed objects [OK]
Hint: GsonConverterFactory parses JSON to objects [OK]
Common Mistakes:
  • Expecting raw JSON instead of parsed objects
  • Forgetting to add converter factory
  • Not understanding suspend functions
4. Identify the error in this Retrofit setup code:
val retrofit = Retrofit.Builder()
  .baseUrl("https://api.example.com")
  .addConverterFactory(GsonConverterFactory)
  .build()
medium
A. Missing parentheses after GsonConverterFactory
B. baseUrl should not have a trailing slash
C. Retrofit.Builder() should be Retrofit.newBuilder()
D. build() should be called before addConverterFactory

Solution

  1. Step 1: Check addConverterFactory usage

    GsonConverterFactory is a class; it requires calling create() method or parentheses to instantiate.
  2. Step 2: Verify other parts

    baseUrl can have or not have trailing slash; Retrofit.Builder() is correct; build() must be last.
  3. Final Answer:

    Missing parentheses after GsonConverterFactory -> Option A
  4. Quick Check:

    addConverterFactory needs instance, not class [OK]
Hint: Call create() on converter factory class [OK]
Common Mistakes:
  • Passing class instead of instance to addConverterFactory
  • Confusing baseUrl format
  • Wrong order of builder methods
5. You want to create a Retrofit instance that supports both JSON and XML responses. Which setup correctly adds both converters?
hard
A. Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(SimpleXmlConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build()
B. Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(GsonConverterFactory.create()).addConverterFactory(SimpleXmlConverterFactory).build()
C. Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(GsonConverterFactory).addConverterFactory(SimpleXmlConverterFactory).build()
D. Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(GsonConverterFactory.create()).build().addConverterFactory(SimpleXmlConverterFactory.create())

Solution

  1. Step 1: Understand converter order importance

    Retrofit tries converters in order added. XML converter should come first to handle XML, then JSON.
  2. Step 2: Check method chaining and instantiation

    Converters must be instantiated with create(). Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(SimpleXmlConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build() adds XML first, then JSON, correctly.
  3. Step 3: Eliminate wrong options

    Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(GsonConverterFactory.create()).addConverterFactory(SimpleXmlConverterFactory.create()).build() reverses order; C misses create() calls; D calls addConverterFactory after build(), which is invalid.
  4. Final Answer:

    Retrofit.Builder().baseUrl("https://api.example.com/").addConverterFactory(SimpleXmlConverterFactory.create()).addConverterFactory(GsonConverterFactory.create()).build() -> Option A
  5. Quick Check:

    Converters order matters; XML first, then JSON [OK]
Hint: Add XML converter before JSON converter [OK]
Common Mistakes:
  • Wrong order of converters causing parsing errors
  • Not calling create() on converters
  • Adding converters after build() call
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard