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
-
Android Studio version 3.6.1
-
Little bit XML and KOTLIN knowledge
-
Android Emulator (or) Android mobile
-
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.
The manifest code is given below,
- <uses-permission android:name="android.permission.INTERNET" />
- <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.
The third party dependencies are given below,
- def retrofit = '2.5.0'
- implementation 'com.squareup.retrofit2:retrofit:' + retrofit
- implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
- implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
-
- def cardview_version = "1.0.0"
- implementation "androidx.legacy:legacy-support-v4:$cardview_version"
- implementation "com.google.android.material:material:$cardview_version"
- 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.
The Code is given below:
- object ApiClient {
- var BASE_URL: String = "https://jsonplaceholder.typicode.com/"
- val getClient: ApiInterface
- 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(ApiInterface::class.java)
- }
- }
Step 4
Create a new Interface for call the API interface.
The API interface code is given below,
- package com.example.recyclerviewjson
- import retrofit2.Call
- import retrofit2.http.GET
- interface ApiInterface {
- @GET("photos")
- fun getPhotos(): Call < List < recyclerresponse >>
- }
Step 5
Create a new model class file to get the response from API
The Model Class is given below,
- package com.example.recyclerviewjson
- import com.google.gson.annotations.SerializedName
- data class recyclerresponse(
-
- @SerializedName("albumId")
- var albumId: kotlin.Int,
- @SerializedName("id")
- var id: kotlin.Int,
- @SerializedName("title")
- val title: String,
- @SerializedName("url")
- val url: String,
- @SerializedName("thumbnailUrl")
- val thumbnailUrl: String)
Step 6
Go to Main Activity.kt. This Kotlin program is the back-end language for your app.
The Kotlin code is given below,
- package com.example.recyclerviewjson
- import android.app.ProgressDialog
- import androidx.appcompat.app.AppCompatActivity
- import android.os.Bundle
- import android.text.Editable
- import android.text.TextWatcher
- import androidx.recyclerview.widget.LinearLayoutManager
- import androidx.recyclerview.widget.RecyclerView
- import kotlinx.android.synthetic.main.activity_main.*
- import retrofit2.Call
- import retrofit2.Callback
- import retrofit2.Response
- class MainActivity: AppCompatActivity() {
- lateinit
- var progerssProgressDialog: ProgressDialog
- var dataList = ArrayList < recyclerresponse > ()
- lateinit
- var recyclerView: RecyclerView
- private
- var myAdapter: DataAdpter ? = null
- override fun onCreate(savedInstanceState: Bundle ? ) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_main)
- recyclerView = findViewById(R.id.brandlist)
- myAdapter = DataAdpter(dataList, this)
- recyclerView.adapter = myAdapter
- recyclerView.layoutManager = LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
- progerssProgressDialog = ProgressDialog(this)
- progerssProgressDialog.setTitle("Loading")
- progerssProgressDialog.setCancelable(false)
- progerssProgressDialog.show()
- getDat1a()
- searchbrandedit.addTextChangedListener(object: TextWatcher {
- override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
- override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
- override fun afterTextChanged(editable: Editable) {
-
- filter(editable.toString())
- }
- })
- }
- private fun getDat1a() {
- val call: Call < List < recyclerresponse >> = ApiClient.getClient.getPhotos()
- call.enqueue(object: Callback < List < recyclerresponse >> {
- override fun onResponse(call: Call < List < recyclerresponse >> ? , response : Response < List < recyclerresponse >> ? ) {
- progerssProgressDialog.dismiss()
- dataList.addAll(response!!.body() !!)
- recyclerView.adapter!!.notifyDataSetChanged()
- }
- override fun onFailure(call: Call < List < recyclerresponse >> ? , t : Throwable ? ) {
- progerssProgressDialog.dismiss()
- }
- })
- }
- private fun filter(text: String) {
-
- val filteredNames = ArrayList < recyclerresponse > ()
-
- dataList!!.filterTo(filteredNames) {
-
- it.title.toLowerCase().contains(text.toLowerCase()) || it.url.toLowerCase().contains(text.toLowerCase())
- }
-
- if (filteredNames != null) {
- myAdapter!!.filterList(filteredNames)
- }
- }
- }
Step 7
Create a new adapter to show the API call to the Frontend.
The Code is given below,
- package com.example.recyclerviewjson
- import android.content.Context
- import android.util.Log
- import android.view.LayoutInflater
- import android.view.View
- import android.view.ViewGroup
- import android.widget.TextView
- import androidx.recyclerview.widget.RecyclerView
- class DataAdpter(private
- var dataList: List < recyclerresponse > , private val context: Context): RecyclerView.Adapter < DataAdpter.ViewHolder > () {
- override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
- return ViewHolder(LayoutInflater.from(context).inflate(R.layout.listcard, parent, false))
- }
- override fun getItemCount(): Int {
- return dataList.size
- }
- override fun onBindViewHolder(holder: ViewHolder, position: Int) {
- val dataModel = dataList.get(position)
- holder.titleTextView.text = dataModel.title
- holder.title.text = dataModel.url
- }
- class ViewHolder(itemLayoutView: View): RecyclerView.ViewHolder(itemLayoutView) {
- lateinit
- var titleTextView: TextView
- lateinit
- var title: TextView
- init {
- titleTextView = itemLayoutView.findViewById(R.id.name)
- title = itemLayoutView.findViewById(R.id.url)
- }
- }
- fun filterList(filteredNames: ArrayList < recyclerresponse > ) {
- Log.e("list", filteredNames.toString())
- Log.e("list", filteredNames.size.toString())
-
- this.dataList = filteredNames
- notifyDataSetChanged()
- }
- }
Step 8
Click the "Run" button, or press Shift+F10 to finally run the project. Choose the "virtual machine" option and click OK.
Conclusion