logo

let’s make something together

Give us a call or drop by anytime, we endeavour to answer all enquiries within 24 hours on business days.

Find us

PO Box 16122 Collins Street West
Victoria 8007 Australia

Email us

info@domain.com
example@domain.com

Phone support

Phone: + (066) 0760 0260
+ (057) 0760 0560

,

How To Use Retrofit On android With Kotlin

  • By Sankar Raman
  • November 29, 2018
  • 1230 Views

 

Kotlin

Kotlin is a statically typed programming language and it’s runs on the Java virtual machine and also can be compiled to JavaScript source code or use the LLVM compiler infrastructure. It’s developed by the team of JetBrains programmers based in Saint Petersburg, Russia.

What Is Retrofit

Retrofit is a REST Client for Java and Android. It sets easy way to retrieve and upload JSON or other structured data via REST based web service. Retrofit automatically serializes the JSON response using a POJO which must be defined in advanced structure on JSON.

Using Retrofit

We have to follow three main classes in retrofit,

  • Model class which is used as a JSON model
  • Interfaces that define the HTTP operations
  • Retrofit Client class

We need to add the following dependencies in our Build.gradle file,

  • compile “com.squareup.retrofit2:retrofit:2.3.0”
  • compile “com.squareup.retrofit2:converter-gson:2.3.0”
  • compile ‘com.squareup.okhttp3:logging-interceptor:3.10.0’

 

API Interface

We need a java interface to make an API call from retrofit, in this API interface we have to define all the URLs with the http request type and parameters.
Here i have listed few type of request details.

Methods To Create API Interface

We should keep all the requests in a separate interface which are needs to be called in backend,

interface APIService {

 

Post Request

@POST("accounts/sign_in")
   fun registrationPost(@Body request: RequestBody): Call<LoginResponse>

 

Put Request

    @PUT()
   fun updateUser(@Url url: String,@Body request: RequestBody): Call<ChangePassword>

 

Delete Request

   @DELETE()
   fun deletelogTime(@Url url: String): Call<DeleteResponse>

 

Get Request

//Fetch all notes
   @GET()
   fun getUserdetails(@Url url: String): Call<UserDetails>
   
   @GET("projects")
   fun getProjectList(@Query("default") default: Boolean): Call<ProjectsList>
     
   @GET("details")
   fun getSummary(@Query("?page_no=1") default: Boolean): Call<SummaryResponse>

 
Query parameters also added with the @Query annotation on a method parameter. They are automatically added at the end of the URL.

   @GET("activities")
   fun getActivityList(): Call<ActivitesResponse>
}

 
Method used to add the standard backend URL or end point,
//**App Utils**

object ApiUtils {
  
   val BASE_URL = "Add your backend end point"
   val apiService: APIService
       get() = RetrofitClient.getClient(BASE_URL)!!.create(APIService::class.java)
}

 

Retrofit Interface

Here we added the application interceptor with header details.

  • To register an application interceptor, we need to call addInterceptor() on OkHttpClient.Builder.
  • To register a Network Interceptor, invoke addNetworkInterceptor() instead of addInterceptor()

 

How To Add API interface into Retrofit Interface,

object RetrofitClient {
 
 var retrofit: Retrofit? = null
   
  fun getClient(baseUrl: String): Retrofit? {
       if (retrofit == null) {
           val interceptor = HttpLoggingInterceptor()
           interceptor.level = HttpLoggingInterceptor.Level.BODY
           val client = OkHttpClient.Builder()
                   .addInterceptor(Interceptor { chain ->
                       val original = chain.request()
                       //header
                       val request = original.newBuilder()
                               .header("Content-Type", "application/json")
                               .header("access-token", Utils.access_token)
                               .header("client", Utils.client)
                               .header("expiry", Utils.expiry)
                               .header("uid", Utils.uid)
                               .method(original.method(), original.body())
                               .build()
                       return@Interceptor chain.proceed(request)
                   })
                   .addInterceptor(interceptor)
                   .connectTimeout(100, TimeUnit.SECONDS)
                   .readTimeout(100, TimeUnit.SECONDS)
                   .build()
           retrofit = Retrofit.Builder()
                   .baseUrl(ApiUtils.BASE_URL)
                   .client(client)
                   .addConverterFactory(GsonConverterFactory.create())
                   .build()
       }
       return retrofit
   }
}

 
The getClient() method will be called every time while setting up a Retrofit interface. Retrofit provides with a list of annotations for each of the HTTP methods: @GET, @POST, @PUT, @DELETE.

Tips & Tricks: Reduce Overdraw From Your Android Application

 

Sample Login Code For Kotlin Using Retrofit

Pass the username and password through json format, json is a lightweight data-interchange format.

XML Code

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".LoginActivity">
   <LinearLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:background="@color/loginBackground"
       android:gravity="center"
       android:orientation="vertical"
       app:layout_constraintBottom_toBottomOf="parent"
       app:layout_constraintLeft_toLeftOf="parent"
       app:layout_constraintRight_toRightOf="parent"
       app:layout_constraintTop_toTopOf="parent">
       <android.support.v7.widget.AppCompatTextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:gravity="center"
           android:text=""
           android:textSize="@dimen/_20sdp" />
       <android.support.v7.widget.AppCompatTextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginTop="@dimen/_5sdp"
           android:gravity="center"
           android:text="@string/login_session"
           android:textSize="@dimen/_15sdp" />
       <android.support.v7.widget.CardView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_margin="@dimen/_10sdp"
           app:cardCornerRadius="@dimen/_2sdp">
           <LinearLayout
               android:layout_width="match_parent"
               android:layout_height="wrap_content"
               android:layout_margin="@dimen/_5sdp"
               android:orientation="vertical">
               <android.support.design.widget.TextInputLayout
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:layout_margin="@dimen/_5sdp">
                   <android.support.design.widget.TextInputEditText
                       android:id="@+id/log_email"
                       android:layout_width="match_parent"
                       android:layout_height="wrap_content"
                       android:layout_marginTop="@dimen/_10sdp"
                       android:drawableStart="@drawable/ic_email_black_24dp"
                       android:drawablePadding="@dimen/_10sdp"
                       android:hint="@string/login_email"
                       android:inputType="textEmailAddress"
                       android:maxLength="30"
                       android:maxLines="1"
                       android:text="" />
               </android.support.design.widget.TextInputLayout>
               <View
                   android:layout_width="match_parent"
                   android:layout_height="@dimen/_1sdp"
                   android:layout_marginTop="@dimen/_5sdp"
                   android:background="#eee">
               </View>
               <android.support.design.widget.TextInputLayout
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:layout_margin="@dimen/_5sdp">
                   <android.support.v7.widget.AppCompatEditText
                       android:id="@+id/log_password"
                       android:layout_width="match_parent"
                       android:layout_height="wrap_content"
                       android:layout_marginTop="@dimen/_12sdp"
                       android:drawableStart="@drawable/ic_lock_outline_black_24dp"
                       android:drawablePadding="@dimen/_10sdp"
                       android:hint="@string/login_pass"
                       android:inputType="textPassword"
                       android:maxLength="30"
                       android:maxLines="1"
                       android:imeOptions="actionDone"
                       android:text="" />
               </android.support.design.widget.TextInputLayout>
               <android.support.v7.widget.AppCompatButton
                   android:id="@+id/go"
                   style="@style/Widget.AppCompat.Button.Colored"
                   android:layout_width="match_parent"
                   android:layout_height="@dimen/_42sdp"
                   android:layout_marginTop="@dimen/_10sdp"
                   android:background="@color/colorPrimary"
                   android:onClick="login"
                   android:padding="@dimen/_2sdp"
                   android:text="@string/login_sigin"
                   android:textAllCaps="true"
                   android:textSize="@dimen/_14sdp"
                   android:textStyle="bold"
                   tools:ignore="RtlHardcoded" />
               <android.support.v7.widget.AppCompatTextView
                   android:layout_width="match_parent"
                   android:layout_height="wrap_content"
                   android:layout_margin="@dimen/_7sdp"
                   android:onClick="forgotPassword"
                   android:text="@string/login_forgot"
                   android:textColor="@color/colorPrimary"
                   android:textSize="@dimen/_14sdp"
                   android:textStyle="bold" />
           </LinearLayout>
       </android.support.v7.widget.CardView>
   </LinearLayout>
</android.support.constraint.ConstraintLayout>

 

Kotlin Code

class LoginActivity : AppCompatActivity() {
private var etEmail: TextInputEditText? = null
private var etlog_Email: AppCompatEditText? = null
private var etlog_Pass: AppCompatEditText? = null
private var btn_login: AppCompatButton? = null
private var util: Utils? = null
override fun onCreate(savedInstanceState: Bundle?) {
   super.onCreate(savedInstanceState)
   this.requestWindowFeature(Window.FEATURE_NO_TITLE)
   setContentView(R.layout.activity_login)
   etlog_Email = findViewById(R.id.log_email)
   etlog_Pass = findViewById(R.id.log_password)
   btn_login = findViewById(R.id.go)
   util = Utils;
   util!!.main(applicationContext)
   
if (!util!!.get_emp_email().isEmpty() && !util!!.get_password().isEmpty()) {
       etlog_Email!!.setText(util!!.get_emp_email())
       etlog_Pass!!.setText(util!!.get_password())
    }
}
}

 

Validation Code

fun login(view: View) {
   hideKeyboard(btn_login!!)
   if (Utils.isNet(applicationContext)) {
       val eMail = etlog_Email?.text.toString()
       val ePass = etlog_Pass?.text.toString()
       if (isValidEmail(eMail)) {
           if (!ePass.isEmpty()) {
               loginAuthendication(eMail, ePass, view)
           } else {
       Snackbar.make(view, "Please enter the password", Snackbar.LENGTH_SHORT).show()
           }
       } else {
       Snackbar.make(view, "Please check the Email ID", Snackbar.LENGTH_SHORT).show()
       }
   } else {
       Snackbar.make(view, R.string.nointernet, Snackbar.LENGTH_SHORT).show()
   }
}

 

Best To Read: How To Improve The Quality Of Android Apps Using Firebase Test Lab

 

Post Request Using Retrofit

fun loginAuthendication(eMail: String, ePass: String, view: View) {
   try {
       Utils.showProgress(this@LoginActivity, "Please wait...")
       val json = JSONObject()
       json.put("email", eMail)
       json.put("password", ePass)
val requestBody: RequestBody = RequestBody.create(MediaType.parse("application/json"), json.toString())
       val call: Call<LoginResponse> = apiService.registrationPost(requestBody)
       call.enqueue(
               object : Callback<LoginResponse> {
                   @SuppressLint("CommitPrefEdits")
                   override fun onResponse(call: Call<LoginResponse>?, response: Response<LoginResponse>?) {
                       if (response!!.isSuccessful) {
                         
                  startActivity(Intent(this@LoginActivity, MainActivity::class.java))
                  finish()
                           //finishAndRemoveTask()
                       } else {
                          
                       }
                   }
                  override fun onFailure(call: Call<LoginResponse>?, t: Throwable?) {
                       Log.d("loginAuthendication", "failure--" + t.toString())
                       Utils.dismissLoader(this@LoginActivity)
                       
                   }
               })
   } catch (e: Exception) {
       Log.d("loginAuthendication", e.toString())
       Utils.dismissLoader(this@LoginActivity)
   }
}

 
The above Android P version requires small changes to do in manifest file because this version google also added the network security feature. So, incase if you don’t want to get blocked by the network security then you can simply add the below code in application tag (manifest) and set the value to be true,

android:usesCleartextTraffic="true"

 
Retrofit is the powerful network library that can easily connect to HTTP-based API services from your Android App and it will greatly help us in handling API requests which is faster in performance and easy to develop, also it helping us to eliminate the boilerplate code in development so start integrating Retrofit on Kotlin today.
 
Want to create a successful mobile app for your business? Make a wise decision when choosing a developer for your app. Call our experts for collaboration right now.

 

Avatar

Sankar Raman

A full stack Android app developer having 4 years of experience in Mobile app development. Well amalgamated Co-worker who rapidly commutes in developing, implementing and adopting new technologies to wider possibilities of App development.

2 thoughts on “How To Use Retrofit On android With Kotlin”

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × four =