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.