Retrofit implementation

How to implement Retrofit in an Android app

For a more complete and in-depth explanation, check out our complete Retrofit course

Download the starter project here

Github repository

Create the POJO class

We’re going to put in place all the components we need so that we can perform a call to the api, retrieve that information, parse it in a certain way so that we can display it on our application.

The first thing we’re going to do is create the POJO, which is simply the object that will store the information that is retrieved from the backend api.

We’re going to put everything that relates to Retrofit inside our model package.

Create a new file named ApiCallResponse

data class ApiCallResponse(

    val method: String?,

    val query: Map<String, String>?,

    @SerializedName(“headers”)

    val heads: Map<String, String>?,

    val body: Map<String, String>?

)

Implementing the interface

Create a new file in the model package and call it ApiCall. This is where we define the methods that we can call on this endpoint.

interface ApiCall {

    @GET(“apiCall”)

    fun callGet(): Call<ApiCallResponse>

}

The return object Call will give us the information from the Api that is parsed into an object ApiCallResponse.

Implementing the service

Let’s put in place the last component as well. Create a new Kotlin file called ApiCallService and make it a singleton. Create a variable BASE_URL that will point to the called url.

object ApiCallService {

    private val BASE_URL = “https://us-central1-apis2-e78c3.cloudfunctions.net”

    private var api = Retrofit.Builder()

        .baseUrl(BASE_URL)

        .addConverterFactory(GsonConverterFactory.create())

        .build()

        .create(ApiCall::class.java)

    fun call() = api.callGet()

}

Putting everything together

Ok so we’re going to put together everything we have so far in order to actually run our application and see the response from the backend Api. In order to do that we need two things.

  • Call the api to retrieve the response and convert it into the object we defined earlier, which is the ApiCallResponse
  • We then need to convert this object into a list of elements that we can display on our app’s RecyclerView

We will call our api from the MainViewModel class. The function fetchData() is invoked by the MainActivity when it needs to retrieve some information. Replace the code in that function with the apiCall.

fun fetchData() {

    loading.value = true

    val call = ApiCallService.call()

    call.enqueue(object: Callback<ApiCallResponse> {

        override fun onResponse(call: Call<ApiCallResponse>, response: Response<ApiCallResponse>) {

            val body = response.body()

            apiResponse.value = body?.flatten()

            error.value = null

            loading.value = false

        }

        override fun onFailure(call: Call<ApiCallResponse>, t: Throwable) {

            onError(t.localizedMessage)

        }

    })

}

In the ApiCallResponse we will then implement the fetchData() method.

    fun flatten(): List<Item> {

        val flatpack = arrayListOf<Item>()

        method?.let { flatpack.add(Item(“method”, method, TYPE_ITEM)) }

        query?.let {

            if (!query.values.isEmpty()) {

                flatpack.add(Item(“query”, “”, TYPE_CATEGORY))

                addMapItems(query, flatpack)

            }

        }

        heads?.let {

            if (!heads.values.isEmpty()) {

                flatpack.add(Item(“headers”, “”, TYPE_CATEGORY))

                addMapItems(heads, flatpack)

            }

        }

        return flatpack

    }

 

    private fun addMapItems(map: Map<String, String>, flatpack: ArrayList<Item>) {

        for (key in map.keys) {

            flatpack.add(Item(key, map.getValue(key), TYPE_ITEM))

        }

    }

Run the code

That is all that is required for this app to work. Let’s run the app and see the outcome.

extra how to gif

For a more complete and in-depth explanation, check out our complete Retrofit course

Close Bitnami banner
Bitnami