In this example, I will show you how to call Retrofit service and display download data into RecyclerView.
Kotlin Retrofit Service Example Video
- You can also go through this video explanation.
Kotlin Retrofit Service 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:- modelPostsDataModel.ktCreate new class PostsDataModel.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 PostsDataModel(
@Expose
@SerializedName("userId")
val userId: Integer,
@Expose
@SerializedName("id")
val id: Integer,
@Expose
@SerializedName("title")
val title: String,
@Expose
@SerializedName("body")
val body: String
)Step 4:Create new Layout:- posts_data_row.xmlCreate new posts_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_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:justificationMode="inter_word"
android:textSize="18dp" />
<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="20dp" />
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>Step 5:Create new Package:- adapterPostsDataAdapter.ktCreate new class PostsDataAdapter.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.R
import com.kotlinkatta.retrofitget.model.PostsDataModel
import kotlinx.android.synthetic.main.posts_data_row.view.*
class PostsDataAdapter (val userList: List<PostsDataModel>) : RecyclerView.Adapter<PostsDataAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.posts_data_row, parent, false)
return ViewHolder(v)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val usermodel : PostsDataModel = userList[position]
holder.txt_title.text = "Title :" + usermodel.title
holder.txt_body.text = "Body :" + usermodel.body
}
override fun getItemCount(): Int {
return userList.size
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val txt_title = itemView.txt_title
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.PostsDataModel
import retrofit2.Call
import retrofit2.http.GET
interface DataService {
@GET("/posts")
fun getAllPhotos(): Call<List<PostsDataModel>>
}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.retrofitget
import android.os.Bundle
import android.view.View
import android.widget.ProgressBar
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.kotlinkatta.retrofitget.adapter.PostsDataAdapter
import com.kotlinkatta.retrofitget.model.PostsDataModel
import com.kotlinkatta.retrofitget.retofitdata.DataService
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
fun_getPhotoData()
}
private fun fun_getPhotoData() {
progress_bar.visibility = View.VISIBLE
val service: DataService = RetrofitClient.retrofitInstance!!.create(DataService::class.java)
val call: Call<List<PostsDataModel>> = service.getAllPhotos()
call.enqueue(object : Callback<List<PostsDataModel>> {
override fun onResponse(call: Call<List<PostsDataModel>>,response: Response<List<PostsDataModel>>) {
val adapter = PostsDataAdapter(response.body()!!)
recyclerView.adapter = adapter
progress_bar.visibility = View.GONE
}
override fun onFailure(call: Call<List<PostsDataModel>>, 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