'How to add search functionality in recyclerViewAdapter

I have a recycler view adapter which displays list of cat information, onlything displayed is the NAME and the image.

I want to search based on the Name.

I have added an search menu item, how can I do the search in the adapter

This is my RecyclerViewAdapter

class RecyclerViewAdapter : RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder>() {

    private var items = ArrayList<CatBreed>()
    var onItemClick: ((CatBreed) -> Unit)? = null

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val binding = CatBreedRowBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return MyViewHolder(binding)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bind(items[position])
        holder.itemView.setOnClickListener {
            Log.d("adapter", "item clicked")
            onItemClick?.invoke(items[position])
        }
    }

    override fun getItemCount(): Int {
        return items.size
    }

    fun setUpdatedData(items: ArrayList<CatBreed>) {
        this.items = items
        notifyDataSetChanged()
    }

    inner class MyViewHolder(private val binding: CatBreedRowBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(data: CatBreed) {
            binding.tvName.text = data.name

            Picasso.get()
                .load(data.image.url)
                .into(binding.imageThumb)
        }
    }
}

added menu item through MainActivity

 override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_item, menu)
        return true
    }

could you please suggest how can I filter through the items byt name please

thanks R



Solution 1:[1]

Define a menu XML that would contain the SearchView

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_search"
        android:icon="@android:drawable/ic_menu_search"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"
        android:title="Search"/>
</menu>

In your activity keep a reference to the complete data that is loaded in the RecyclerView and then configure SearchView to update the RecyclerView with filtered list

/* Maintain a reference to the complete CatBreed list */
/* initialize this list when you receive the cat breed data for first time */
private lateinit var completeList: List<CatBreed>

/* Now configure the SearchView to update the RecyclerView */
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.activity_menu, menu)
    val searchItem = menu?.findItem(R.id.action_search)
        
    val searchView = searchItem!!.actionView as SearchView
    searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {

        override fun onQueryTextSubmit(query: String?): Boolean {
            /* If user cleared the search then set the complete list on RV */
            if(query.isNullOrEmpty()){
                 adapter.setUpdatedData(ArrayList(completeList))
            }
            else {
                  val filteredList = completeList.filter { it.name.startsWith(query) }
                  adapter.setUpdatedData(ArrayList(filteredList))
            }
            return true
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            Log.d("MainActivity", "Text Change")
            return true
        }
    })
    return true
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mightyWOZ