How To Load The Data To Recyclerview And Search The Data In Kotlin Android - Part Two

Introduction

 
Android is an open-source operating system based on Linux with a Java programming interface for mobile devices such as Smartphone (Touch Screen Devices who supports Android OS) as well for Tablets. With over 85% market share worldwide, Android Operating System dominates the mobile platform market. Today, I will show you how to load the Data to RecyclerView and search the Data in Kotlin Android. In this Part i will show the Backend.
Requirements
Steps to be followed.
 
Follow these steps to load the Data to RecyclerView and search the Data in Kotlin Android Backend.
 
Step 1
 
Go to the manifest file and add the dependency for an internet connection.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The manifest code is given below,
  1. <uses-permission android:name="android.permission.INTERNET" />    
  2. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />   
Step 2
 
Go to the build.grade file. Add third party dependencies for retrofit and card view.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The third party dependencies are given below,
  1. def retrofit = '2.5.0'    
  2. implementation 'com.squareup.retrofit2:retrofit:' + retrofit    
  3. implementation 'com.squareup.retrofit2:converter-gson:2.5.0'    
  4. implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'    
  5.     
  6. def cardview_version = "1.0.0"    
  7. implementation "androidx.legacy:legacy-support-v4:$cardview_version"    
  8. implementation "com.google.android.material:material:$cardview_version"    
  9. implementation "androidx.cardview:cardview:$cardview_version"    
Step 3
 
Create a new Class file. And name it as ApiClient. This class file used for API Client call which is used to call the API from the server.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The Code is given below:
  1. object ApiClient {  
  2.     var BASE_URL: String = "https://jsonplaceholder.typicode.com/"  
  3.     val getClient: ApiInterface  
  4.     get() {  
  5.         val gson = GsonBuilder().setLenient().create()  
  6.         val interceptor = HttpLoggingInterceptor()  
  7.         interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)  
  8.         val client = OkHttpClient.Builder().addInterceptor(interceptor).build()  
  9.         val retrofit = Retrofit.Builder().baseUrl(BASE_URL).client(client).addConverterFactory(GsonConverterFactory.create(gson)).build()  
  10.         return retrofit.create(ApiInterface::class.java)  
  11.     }  
  12. }  
Step 4
 
Create a new Interface for call the API interface.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The API interface code is given below,
  1. package com.example.recyclerviewjson  
  2. import retrofit2.Call  
  3. import retrofit2.http.GET  
  4. interface ApiInterface {  
  5.     @GET("photos")  
  6.     fun getPhotos(): Call < List < recyclerresponse >>  
  7. }  
Step 5

Create a new model class file to get the response from API
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The Model Class is given below,
  1. package com.example.recyclerviewjson    
  2. import com.google.gson.annotations.SerializedName    
  3. data class recyclerresponse(    
  4.     
  5. @SerializedName("albumId")    
  6. var albumId: kotlin.Int,    
  7. @SerializedName("id")    
  8. var id: kotlin.Int,    
  9. @SerializedName("title")    
  10. val title: String,    
  11. @SerializedName("url")    
  12. val url: String,    
  13. @SerializedName("thumbnailUrl")    
  14. val thumbnailUrl: String)    
Step 6
 
Go to Main Activity.kt. This Kotlin program is the back-end language for your app.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The Kotlin code is given below,
  1. package com.example.recyclerviewjson  
  2. import android.app.ProgressDialog  
  3. import androidx.appcompat.app.AppCompatActivity  
  4. import android.os.Bundle  
  5. import android.text.Editable  
  6. import android.text.TextWatcher  
  7. import androidx.recyclerview.widget.LinearLayoutManager  
  8. import androidx.recyclerview.widget.RecyclerView  
  9. import kotlinx.android.synthetic.main.activity_main.*  
  10.     import retrofit2.Call  
  11. import retrofit2.Callback  
  12. import retrofit2.Response  
  13. class MainActivity: AppCompatActivity() {  
  14.     lateinit  
  15.     var progerssProgressDialog: ProgressDialog  
  16.     var dataList = ArrayList < recyclerresponse > ()  
  17.     lateinit  
  18.     var recyclerView: RecyclerView  
  19.     private  
  20.     var myAdapter: DataAdpter ? = null  
  21.     override fun onCreate(savedInstanceState: Bundle ? ) {  
  22.         super.onCreate(savedInstanceState)  
  23.         setContentView(R.layout.activity_main)  
  24.         recyclerView = findViewById(R.id.brandlist)  
  25.         myAdapter = DataAdpter(dataList, this)  
  26.         recyclerView.adapter = myAdapter  
  27.         recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)  
  28.         progerssProgressDialog = ProgressDialog(this)  
  29.         progerssProgressDialog.setTitle("Loading")  
  30.         progerssProgressDialog.setCancelable(false)  
  31.         progerssProgressDialog.show()  
  32.         getDat1a()  
  33.         searchbrandedit.addTextChangedListener(object: TextWatcher {  
  34.             override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}  
  35.             override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}  
  36.             override fun afterTextChanged(editable: Editable) {  
  37.                 //after the change calling the method and passing the search input    
  38.                 filter(editable.toString())  
  39.             }  
  40.         })  
  41.     }  
  42.     private fun getDat1a() {  
  43.         val call: Call < List < recyclerresponse >> = ApiClient.getClient.getPhotos()  
  44.         call.enqueue(object: Callback < List < recyclerresponse >> {  
  45.             override fun onResponse(call: Call < List < recyclerresponse >> ? , response : Response < List < recyclerresponse >> ? ) {  
  46.                 progerssProgressDialog.dismiss()  
  47.                 dataList.addAll(response!!.body() !!)  
  48.                 recyclerView.adapter!!.notifyDataSetChanged()  
  49.             }  
  50.             override fun onFailure(call: Call < List < recyclerresponse >> ? , t : Throwable ? ) {  
  51.                 progerssProgressDialog.dismiss()  
  52.             }  
  53.         })  
  54.     }  
  55.     private fun filter(text: String) {  
  56.         //new array list that will hold the filtered data    
  57.         val filteredNames = ArrayList < recyclerresponse > ()  
  58.         //looping through existing elements and adding the element to filtered list    
  59.         dataList!!.filterTo(filteredNames) {  
  60.             //if the existing elements contains the search input    
  61.             it.title.toLowerCase().contains(text.toLowerCase()) || it.url.toLowerCase().contains(text.toLowerCase())  
  62.         }  
  63.         //calling a method of the adapter class and passing the filtered list    
  64.         if (filteredNames != null) {  
  65.             myAdapter!!.filterList(filteredNames)  
  66.         }  
  67.     }  
  68. }  
Step 7
 
Create a new adapter to show the API call to the Frontend.
 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android
 
The Code is given below,
  1. package com.example.recyclerviewjson  
  2. import android.content.Context  
  3. import android.util.Log  
  4. import android.view.LayoutInflater  
  5. import android.view.View  
  6. import android.view.ViewGroup  
  7. import android.widget.TextView  
  8. import androidx.recyclerview.widget.RecyclerView  
  9. class DataAdpter(private  
  10.     var dataList: List < recyclerresponse > , private val context: Context): RecyclerView.Adapter < DataAdpter.ViewHolder > () {  
  11.     override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {  
  12.         return ViewHolder(LayoutInflater.from(context).inflate(R.layout.listcard, parent, false))  
  13.     }  
  14.     override fun getItemCount(): Int {  
  15.         return dataList.size  
  16.     }  
  17.     override fun onBindViewHolder(holder: ViewHolder, position: Int) {  
  18.         val dataModel = dataList.get(position)  
  19.         holder.titleTextView.text = dataModel.title  
  20.         holder.title.text = dataModel.url  
  21.     }  
  22.     class ViewHolder(itemLayoutView: View): RecyclerView.ViewHolder(itemLayoutView) {  
  23.         lateinit  
  24.         var titleTextView: TextView  
  25.         lateinit  
  26.         var title: TextView  
  27.         init {  
  28.             titleTextView = itemLayoutView.findViewById(R.id.name)  
  29.             title = itemLayoutView.findViewById(R.id.url)  
  30.         }  
  31.     }  
  32.     fun filterList(filteredNames: ArrayList < recyclerresponse > ) {  
  33.         Log.e("list", filteredNames.toString())  
  34.         Log.e("list", filteredNames.size.toString())  
  35.         // this.dataList.clear()    
  36.         this.dataList = filteredNames  
  37.         notifyDataSetChanged()  
  38.     }  
  39. }  
Step 8
 
Click the "Run" button, or press Shift+F10 to finally run the project. Choose the "virtual machine" option and click OK.
 

Conclusion

 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android 
How To Load The Data To Recyclerview And Search The Data In Kotlin Android


Similar Articles