In this example, I will show you how to call service using Retrofit2 and MutableList and display service data into RecyclerView.
Kotlin Call Service Using Retrofit2 And MutableList Example Video
- You can also go through this video explanation.
Kotlin Call Service Using Retrofit2 And MutableList 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.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:- modelUsersDataModel.ktCreate new class UsersDataModel.kt under model package and Add following code.package com.kotlinkatta.retrofitget.model
import com.google.gson.annotations.SerializedName
data class UsersDataModel(
@SerializedName("id")
val id: Int? = null,
@SerializedName("name")
val name: String? = null,
@SerializedName("username")
val userName: String? = null,
@SerializedName("email")
val email: String? = null,
@SerializedName("address")
val addressObject : address? = null,
@SerializedName("phone")
val phone: String? = null,
@SerializedName("website")
val website: String? = null,
@SerializedName("company")
val companyObject : company? = null,
)
data class address(
@SerializedName("street")
val street: String? = null,
@SerializedName("suite")
val suite: String? = null,
@SerializedName("city")
val city: String? = null,
@SerializedName("zipcode")
val zipCode: String? = null,
@SerializedName("geo")
val geoObject : geo? = null,
)
data class geo(
@SerializedName("lat")
val lat: String? = null,
@SerializedName("lng")
val lng: String? = null,
)
data class company(
@SerializedName("name")
val name: String? = null,
@SerializedName("catchPhrase")
val catchPhrase: String? = null,
@SerializedName("bs")
val bs: String? = null,
)Step 4:Create new Layout:- users_data_row.xmlCreate new users_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:layout_marginTop="3dp"
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:justificationMode="inter_word"
android:textSize="20dp" />
<TextView
android:layout_marginTop="3dp"
android:id="@+id/txt_address_city"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:justificationMode="inter_word"
android:textSize="20dp" />
<TextView
android:layout_marginTop="3dp"
android:id="@+id/txt_geo_lat_lng"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:justificationMode="inter_word"
android:textSize="17dp" />
<TextView
android:layout_marginTop="3dp"
android:id="@+id/txt_company_name"
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:- adapterUsersDataAdapter.ktCreate new class UsersDataAdapter.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.retofitokhttpmutableget.R
import com.kotlinkatta.retrofitget.model.UsersDataModel
import kotlinx.android.synthetic.main.users_data_row.view.*
class UsersDataAdapter(private var userList: MutableList<UsersDataModel>) : RecyclerView.Adapter<UsersDataAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.users_data_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val usersDataModel : UsersDataModel = userList[position]
holder.txt_name.text = "Name : " + usersDataModel.name
holder.txt_email.text = "Email : " + usersDataModel.email
holder.txt_address_city.text = "Address City : " + usersDataModel.addressObject!!.city
holder.txt_geo_lat_lng.text = "Geo Lat : " + usersDataModel.addressObject!!.geoObject!!.lat + " " + "Lat : " + usersDataModel.addressObject!!.geoObject!!.lng
holder.txt_company_name.text = "Company Name : " + usersDataModel.companyObject!!.name
}
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_address_city = itemView.txt_address_city
val txt_geo_lat_lng = itemView.txt_geo_lat_lng
val txt_company_name = itemView.txt_company_name
}
}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.UsersDataModel
import retrofit2.Call
import retrofit2.http.GET
interface DataService {
@GET("/users")
fun getUsersData(): Call<MutableList<UsersDataModel>>
}Step 7:RetrofitClient.ktCreate new class RetrofitClient.kt under retofitdata package and Add following code.package com.kotlinkatta.retrofitget.retofitdata
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
object RetrofitClient {
var retrofit: Retrofit? = null
var base_url = "https://jsonplaceholder.typicode.com"
val retrofitInstance: Retrofit
get() {
if (retrofit == null) {
retrofit = Retrofit.Builder()
.baseUrl(base_url)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return retrofit!!
}
}Step 8:MainActivity.ktAdd following code into MainActivity.kt.package com.kotlinkatta.retofitgetmutablelist
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.UsersDataAdapter
import com.kotlinkatta.retrofitget.model.UsersDataModel
import com.kotlinkatta.retrofitget.retofitdata.DataService
import com.kotlinkatta.retrofitget.retofitdata.RetrofitClient
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
var listUsers: MutableList<UsersDataModel> = mutableListOf<UsersDataModel>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
listUsers = mutableListOf()
progress_bar = findViewById<ProgressBar>(R.id.progress_bar)
recyclerView = findViewById<RecyclerView>(R.id.recyclerview)
layoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = layoutManager
funGetUsersData()
}
private fun funGetUsersData() {
progress_bar.visibility = View.VISIBLE
val service: DataService = RetrofitClient.retrofitInstance!!.create(DataService::class.java)
val call: Call<MutableList<UsersDataModel>> = service.getUsersData()
call.enqueue(object : Callback<MutableList<UsersDataModel>> {
override fun onResponse(call: Call<MutableList<UsersDataModel>>,response: Response<MutableList<UsersDataModel>>) {
val adapter = UsersDataAdapter(response.body()!!)
recyclerView.adapter = adapter
progress_bar.visibility = View.GONE
}
override fun onFailure(call: Call<MutableList<UsersDataModel>>, 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