Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Use Retrofit in Kotlin Android App Development - 4 Easy Steps

    • 0
    • 0
    • 0
    • 0
    • 3
    • 0
    • 1
    • 0
    • 2.65k
    Comment on it

    Retrofit is a library which is very easy to use an apply. It helps to convert the HTTP API into a Kotlin interface. Though many of us must have used retrofit in Android but now as Google has announced Kotlin as an official language for Android App Development. So, let's see how to use Retrofit in Kotlin.

     

     

     

     

    Following is a simple demo for integrating retrofit in kotlin, You can easily integrate it in your code by following the below mentioned steps.

     

    Step  1: Add the compile statement for retrofit in build.gradle file.

     

    Eg.

    compile 'com.squareup.retrofit2:converter-gson:2.0.2'
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    compile 'com.google.code.gson:gson:2.7'
    
    // At the time of writing this blog above is the latest version of retrofit.
    

     

     

    Step 2:  Create recyclerview inside your main activity xml.

    Eg.

    <android.support.v7.widget.RecyclerView
       android:id="@+id/recycler_view"
       android:layout_width="match_parent"
       android:layout_height="match_parent"/>
    

     

    Step 3: Create a request method to request for the api call.

     

    Eg.

    /**
        * try to login user on server with the username and password provided
        */
       fun getGitUsers(since : Int, callback: ApiCallback) {
           val callSaveRoute = apiClient.getGitUsers(since)
           val connectionManager = ConnectionManager.getConnectionInstance(callSaveRoute)
           connectionManager.callApi(object : BaseListener.OnWebServiceCompleteListener {
               override fun onWebServiceComplete(baseObject: ResponseBody) {
                   try {
    //                    val jsonObj = JSONObject(baseObject.string().substring(baseObject.string().indexOf("{"), baseObject.string().lastIndexOf("}") + 1))
                       val jsonObject = JSONArray(baseObject.string())
                       Log.e("git response ", " "+jsonObject.toString())
    
                       val gsonBuilder = GsonBuilder()
                       val gson = gsonBuilder.create()
    
                       val testCase = gson.fromJson(jsonObject.toString(), Array<UserBean>::class.java)
    
    
    //                    val routeModal = gsonBuilder.fromJson(jsonObject.toString(), UserBeanResponse::class.java)
                       callback.onUserSuccess(testCase)
                   } catch (exp: Exception) {
                       exp.printStackTrace()
                       callback.onRequestFailed("Error occurred while parsing")
                   }
    
               }
    
               override fun onWebStatusFalse(message: String) {
                   callback.onRequestFailed(message)
               }
           })
       }
    

     

    This method will requires two params first one is of integer type which is no of profiles you want to see, and second one is a call back to deliver the result back.

     

     

    Step 4: Create Adapter for the recyclerview to show the response you received from api.

     

    Eg.

    /**
    * Created by amitrai on 22/8/17.
    * used for :-
    */
    
    class UsersAdapter(userBean: Array<UserBean>, app_context: Context) : RecyclerView.Adapter<UsersAdapter.ViewHolder>(){
    
       val userList = userBean
       val context: Context = app_context
    
       override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
           val view = LayoutInflater.from(parent!!.context).inflate(R.layout.user_profile,
                   parent, false)
    
           return ViewHolder(view)
       }
    
       override fun getItemCount(): Int {
           return userList.size
       }
    
       override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
           holder?.bindItems(userList[position], context)
       }
    
    
       //the class is hodling the list view
       class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
    
    
           fun bindItems(user: UserBean, context: Context) {
               val textViewName = itemView.findViewById<TextView>(R.id.txt_name) as TextView
               val txt_id  = itemView.findViewById<TextView>(R.id.txt_id) as TextView
               val img_profile  = itemView.findViewById<ImageView>(R.id.img_profile) as ImageView
               textViewName.text = user.login
               txt_id.text = user.type
    
    
               Glide.with(context).load(user.avatarUrl).into(img_profile)
           }
       }
    }
    

     

    Now just make call from you button click or any event to the method you have created in step 3 and you are done.

     

    Following is a link to a complete working demo of retrofit in kotlin.

    https://github.com/amitrai98/KotlinRecyclerView

     

    If you have any queries feel free to write in comments.

     

    Happy coding :)

    How to Use Retrofit in Kotlin Android App Development - 4 Easy Steps

 3 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: