TheJadav

android retrofit example

Make your first API call using retrofit

Add retrofit and GsonConverter in your project

why to use GsonConverter here?. It will be useful for converting JsonObject directly to Java class or Kotlin class. So, we only need to pass our models.

implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.google.code.gson:gson:2.8.5'

Make your first API call using retrofit

Add retrofit and GsonConverter in your project

why to use GsonConverter here?. It will be useful for converting JsonObject directly to Java class or Kotlin class. So, we only need to pass our models.

implementation 'com.squareup.retrofit2:retrofit:2.6.2'
implementation 'com.squareup.retrofit2:converter-gson:2.6.2'
implementation 'com.google.code.gson:gson:2.8.5'

Single instance object retrofit

What it means by single instance? We will use single instance in whole project.

   fun getRetrofitInstance() : Retrofit{
        if(retrofit == null){
            retrofit = Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
        return retrofit!!
    }

Create interface for Api calling. 

This will include modelclass for login as well as response for api call

interface ApiInterface {
    @POST("LoginApi/LoginSubmit")
    fun login(@Body params: LoginParams) : Call
}

Call Api with retrofit

this is final step. You need to create instance of ApiInterface with retrofit and make api call.

        val apiInterface = ApiManager.getClient().create(ApiInterface::class.java)
        val call = apiInterface.login(LoginParams(email, password))


        //For background api call
        call.enqueue(object : Callback {
            override fun onFailure(call: Call, t: Throwable) {
                //handle failure
            }

            override fun onResponse(call: Call, response: Response) {
                //Enjoy success
                //response.body have your LoginResponse object
            }
        })

       //For same thread api call
       val response  = call.execute()

Share this content:

Share:

More Posts

How does data persistence work in Android?

Data persistence in Android is the ability to save data to the device so that it can be accessed later, even if the app is closed or the device is restarted. There are several ways to achieve data persistence in Android

Fragments and Activities: Two Pillars of Android Development

Fragments and Activities are both important components of Android development. Fragments are a good choice for creating reusable and dynamic UIs, while Activities are a good choice for managing the lifecycle of an app’s UI and implementing core features.

Table of Contents

Send Us A Message