Retrofit Integration in Android - Kotlin

Retrofit is a Networking library, which is faster to use and easier to develop.

Let’s see how to integrate Retrofit in Android with Kotlin.

If you'd like to integrate RxJava as well, you can check here.

1. Configure:

  • Include the following in app-level build.gradle.

build.gradle



compile "com.squareup.retrofit2:retrofit:2.3.0"
compile "com.squareup.retrofit2:converter-gson:2.3.0"


  • Include internet permission in Manifest file.


AndroidManifest.xml



<uses-permission android:name="android.permission.INTERNET" />

2. Preparing Helper classes:

ApiInterface.kt



interface ApiInterface {
   @POST("get_users_detail") // Your url
   fun getUser(@Body requestBody: RequestBody): Call<UserResponse>
}

Model classes:

                     Response from Retrofit will be stored in POJO classes directly.

UserResponse.kt



data class UserResponse(var httpCode: String, var user: ArrayList<User>)


User.kt



data class User(val name: String, val phone: String)


3. Code

                           Here, the request parameters will be sent to api in the type of RequestBody, but you can send in any type as you wish. And GsonConverterFactory will convert the response as UserResponse pojo, that we can read.

RetrofitDemo.kt



class RetrofitDemo : AppCompatActivity() {


   private var list: ArrayList<User?> = ArrayList<User?>()
   lateinit var adapter: RecyclerAdapter
   lateinit var retrofit : Retrofit
   var url : String = "xxxxxxxxxx" // Your Base Url Ex: htttp://xxexample.com/api/
   lateinit var apiService : ApiInterface


   override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) {
       super.onCreate(savedInstanceState, persistentState)


       setContentView(R.layout.recycler)

       retrofit = Retrofit.Builder()
               .baseUrl(url)
               .addConverterFactory(GsonConverterFactory.create())
               .build()


       recyclerView.layoutManager = LinearLayoutManager(this, LinearLayout.VERTICAL, false)
       adapter = RecyclerAdapter(this, list);
       recyclerView.adapter = adapter


       callApi()


   }


   private fun callApi() {
       val json = JSONObject()
       json.put("id","20")


       val requestBody : RequestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), json.toString())


       apiService = retrofit.create(ApiInterface::class.java)
       val call : Call<UserResponse> = apiService.getUser(requestBody)
       call.enqueue(object : Callback<UserResponse> {
           override fun onFailure(call: Call<UserResponse>?, t: Throwable?) {
               Toast.makeText(this@RetrofitDemo, t!!.message,Toast.LENGTH_SHORT).show()
           }


           override fun onResponse(call: Call<UserResponse>?, response: Response<UserResponse>?) {
               val data : UserResponse? = response!!.body()
               if(data!!.httpCode.equals("200")) {
                   list.addAll(data.user);
                   adapter.notifyDataSetChanged()
               }else{
                   Toast.makeText(this@RetrofitDemo, getString(R.string.something_wrong),Toast.LENGTH_SHORT).show()


               }
           }


       });
   }


   class RecyclerAdapter(val context: Context, val data: ArrayList<User?>) : RecyclerView.Adapter<RecyclerAdapter.ViewHolder>() {


       override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
           if (holder != null)
               holder.bindItems(data.get(position))
       }


       override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
           val v = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false)
           return ViewHolder(v)
       }


       override fun getItemCount(): Int {
           return data.size
       }


       class ViewHolder(itemView: View?) : RecyclerView.ViewHolder(itemView) {
           fun bindItems(map: User?) {
               itemView.itemid.text = map!!.name
               itemView.name.text = map.phone
           }
       }


   }
}


4. Run Application:

Finally run the application.

retrofit.png

Comments

Post a Comment

Popular posts from this blog

SOAP Client using ksoap2 in Android - Kotlin

RecyclerView with different number of columns using SpanSizeLookup

Map, Location update and AutoComplete Places - Kotlin

Stripe Integration in Android - Kotlin

TabLayout in Android with Kotlin

Room with LiveData, ViewModel - Android Architecture Components - Kotlin

Exploring Databinding Library in Android - Kotlin

Android JetPack - Scheduling Tasks with WorkManager

FCM Integration in Android - Kotlin

Using Camera in Android - Kotlin