In this example, I will show you how to call Retrofit2 service using okhttp3 and display download data into RecyclerView.
Kotlin Call Retrofit2 Service Using okhttp3 Example Video
- You can also go through this video explanation.
Kotlin Call Retrofit2 Service Using OKHTTP3 Method(Get) Example
Creating a New Project
- So first create a new Android Studio project using Kotlin.
- Once the project is loaded come inside the activity_main.xml and remove the Hello World TextView.
Android studio project screen
JSON Service Url:
Step 1:
Open build.gradle and add following dependency and rebuild the project.
implementation 'com.google.code.gson:gson:2.8.4'
implementation 'com.squareup.okhttp3:logging-interceptor:3.8.0'
implementation 'com.squareup.retrofit2:retrofit:2.3.0'
implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
implementation 'com.google.android.material:material:1.2.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
Step 2:Open AndroidManifest.xml and add Internet Permission.<uses-permission android:name="android.permission.INTERNET"/>Step 3:Create new Package:- modelCommentsDataModel.ktCreate new class CommentsDataModel.kt under model package and Add following code.package com.kotlinkatta.retrofitget.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class CommentsDataModel(
@Expose
@SerializedName("postId")
val postId: Integer,
@Expose
@SerializedName("id")
val id: Integer,
@Expose
@SerializedName("name")
val name: String,
@Expose
@SerializedName("email")
val email: String,
@Expose
@SerializedName("body")
val body: String
)Step 4:Create new Layout:- comments_data_row.xmlCreate new comments_data_row.xml file under layout folder and Add following code.<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<androidx.cardview.widget.CardView
android:layout_margin="10dp"
app:cardCornerRadius="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/colorAccent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp"
android:padding="10dp"
android:background="#ffffff"
android:orientation="vertical">
<TextView
android:id="@+id/txt_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:justificationMode="inter_word"
android:textSize="20dp" />
<TextView
android:layout_marginTop="3dp"
android:id="@+id/txt_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:justificationMode="inter_word"
android:textSize="17dp" />
<TextView
android:layout_marginTop="3dp"
android:id="@+id/txt_body"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:justificationMode="inter_word"
android:textSize="17dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>Step 5:Create new Package:- adapterCommentsDataAdapter.ktCreate new class CommentsDataAdapter.kt under adapter package and Add following code.package com.kotlinkatta.retrofitget.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.kotlinkatta.retrofitget.model.CommentsDataModel
import com.kotlinkatta.retrofitokhttp.R
import kotlinx.android.synthetic.main.comments_data_row.view.*
class CommentsDataAdapter(val userList: List<CommentsDataModel>) : RecyclerView.Adapter<CommentsDataAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.comments_data_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val commentsDataModel : CommentsDataModel = userList[position]
holder.txt_name.text = "Name : " + commentsDataModel.name
holder.txt_email.text = "Email : " + commentsDataModel.email
holder.txt_body.text = "Body : " + commentsDataModel.body
}
override fun getItemCount(): Int {
return userList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txt_name = itemView.txt_name
val txt_email = itemView.txt_email
val txt_body = itemView.txt_body
}
}Step 6:Create new Package:- retofitdataDataService.ktCreate new class DataService.kt under retofitdata package and Add following code.package com.kotlinkatta.retrofitget.retofitdata
import com.kotlinkatta.retrofitget.model.CommentsDataModel
import retrofit2.Call
import retrofit2.http.GET
interface DataService {
@GET("/posts/1/comments")
fun getAllComments(): Call<List<CommentsDataModel>>
}Step 7:RetrofitClient.ktCreate new class RetrofitClient.kt under retofitdata package and Add following code.package com.kotlinkatta.retrofitget.retofitdata
import com.google.gson.GsonBuilder
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
var BASE_URL:String="https://jsonplaceholder.typicode.com"
val getClient: DataService
get() {
val gson = GsonBuilder().setLenient().create()
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
val client = OkHttpClient.Builder().addInterceptor(interceptor).build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build()
return retrofit.create(DataService::class.java)
}
}Step 8:MainActivity.ktAdd following code into MainActivity.kt.package com.kotlinkatta.retrofitokhttp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlinkatta.retrofitget.adapter.CommentsDataAdapter
import com.kotlinkatta.retrofitget.model.CommentsDataModel
import com.kotlinkatta.retrofitget.retofitdata.RetrofitClient
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
class MainActivity : AppCompatActivity() {
lateinit var recyclerView: RecyclerView
lateinit var layoutManager: LinearLayoutManager
lateinit var progress_bar: ProgressBar
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
progress_bar = findViewById<ProgressBar>(R.id.progress_bar)
recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
layoutManager = LinearLayoutManager(this)
recyclerview.layoutManager = layoutManager
funGetCommentsData()
}
private fun funGetCommentsData() {
progress_bar.visibility = View.VISIBLE
val call: Call<List<CommentsDataModel>> = RetrofitClient.getClient.getAllComments()
call.enqueue(object : Callback<List<CommentsDataModel>> {
override fun onResponse(call: Call<List<CommentsDataModel>>, response: Response<List<CommentsDataModel>>) {
val adapter = CommentsDataAdapter(response.body()!!)
recyclerView.adapter = adapter
progress_bar.visibility = View.GONE
}
override fun onFailure(call: Call<List<CommentsDataModel>>, t: Throwable?) {
progress_bar.visibility = View.GONE
}
})
}
}Step 9:activity_main.xmlAdd following code into activity_main.xml.<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
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=".MainActivity">
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent">
</androidx.recyclerview.widget.RecyclerView>
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>OutPut:
Comments
Post a Comment