How to search from SearchView in the actionbar data from RecycleView using Kotlin?

0

Follow the code below:

class MainActivity : AppCompatActivity(), SearchView.OnQueryTextListener {

    var list = ArrayList<Shop>()
    var adapter = ShopAdapter(this, list)
    var imageModelArrayList: ArrayList<Shop>? = null


    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)


        prepareList(list)

        val rView = findViewById(R.id.rView) as RecyclerView

        rView.adapter = adapter

        rView.layoutManager = GridLayoutManager(this, 2, GridLayoutManager.VERTICAL, false)
        //handleIntent(getIntent


    }


    fun prepareList(list: ArrayList<Shop>) {

        list.add(Shop("A beleza da onça pintada", "passeando em seu habitath ", R.drawable.onca_um))
        list.add(Shop("Ternura nos olhos de uma criança", "Simplicidade", R.drawable.children_um))
        list.add(Shop("A beleza dos peixes", "natureza que se reinventa", R.drawable.peixes))
        list.add(Shop("Tarde linda", "espetáculo", R.drawable.tarde_um))

    }


    override fun onCreateOptionsMenu(menu: Menu): Boolean {

        menuInflater.inflate(R.menu.menu_main, menu)
        menu.findItem(R.id.search)

        val searchView = menu.findItem(R.id.search).actionView as? SearchView

        searchView?.setOnQueryTextListener(this)

        return true

    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {

        when (item.itemId) {
            R.id.sobre -> {

                //Toast.makeText(this, "home", Toast.LENGTH_SHORT).show()
                val intent = Intent(this@MainActivity, MainActivity::class.java)

                startActivity(intent)
                return true
            }


        }


        return super.onOptionsItemSelected(item)
    }


    override fun onQueryTextSubmit(query: String): Boolean {

        val tag = "Script"
        Log.i(tag, "onQueryTextSubmit ${query}")

        return false
    }

    override fun onQueryTextChange(newText: String): Boolean {

        Log.i("Script", "onQueryTextChange ${newText}")

//        adapter.filter(listaText)
        adapter.getFilter().filter(newText)
        return true
    }


}

My ShopAdapter, Follow the code below:

/**
 * Created by faro on 9/22/17.
 */


class ShopAdapter(private val context: Context, private val list: List<Shop>) : RecyclerView.Adapter<ShopAdapter.ViewHolder>(), Filterable {

    var shopAdapterFilter = ShopAdapterFilter()

    override fun getFilter(): Filter {

        if (shopAdapterFilter == null) {
            shopAdapterFilter = ShopAdapterFilter()
        }
        return shopAdapterFilter


    }

    class ShopAdapterFilter : Filter() {

        val listShop: List<Shop> = ArrayList<Shop>()
        val arrayShop: ArrayList<Shop>? = null
        private var sShop: List<Shop>? = null

        override fun performFiltering(charSequence: CharSequence?): FilterResults {

            val results = Filter.FilterResults()

            if (charSequence == null || charSequence.isEmpty()) {

                results.values = listShop
                results.count = arrayShop!!.size
            } else {
                val listShopView = ArrayList<Shop>()

                for (l in listShopView) {
                    if (l.name.toLowerCase(Locale.getDefault()).contains(charSequence)) {
                        val main = MainActivity()
                        main.imageModelArrayList!!.add(l)
                    }
                }
                Log.i("Ok", "Ok")
            }

            return results

        }


        override fun publishResults(p0: CharSequence?, p1: FilterResults?) {
            sShop = p1!!.values as List<Shop>?
            //notifyDataSetChanged()


        }

    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        var titleTextView: TextView? = null
        var countTextView: TextView? = null
        var thumbImageView: ImageView? = null
        var subtitleTextView: TextView? = null
        var overflowImageView: ImageView? = null

        init {
            titleTextView = itemView.findViewById<TextView>(R.id.title) as? TextView
            //countTextView = itemView.findViewById<TextView>(R.id.count) as? TextView
            subtitleTextView = itemView.findViewById<TextView>(R.id.subtituloItem) as? TextView
            thumbImageView = itemView.findViewById<ImageView>(R.id.thumbnail) as? ImageView
            overflowImageView = itemView.findViewById<ImageView>(R.id.overflow) as? ImageView
        }
    }


    override fun onCreateViewHolder(parent: ViewGroup, type: Int): ShopAdapter.ViewHolder {

        val view: View = LayoutInflater.from(parent.context).inflate(R.layout.list_row, parent, false);
        val card = view.findViewById<CardView>(R.id.card_view) as CardView

        card.maxCardElevation = 2.0F;
        card.radius = 5.0F;
        return ViewHolder(view);
    }

    override fun onBindViewHolder(holder: ShopAdapter.ViewHolder, position: Int) {

        var album: Shop = list.get(position)

        holder.titleTextView?.text = album.name

        //holder.countTextView?.text = "${album.subTitle} songs"

        holder.subtitleTextView?.text = album.subTitle

        holder.thumbImageView?.setImageResource(album.thumbnail)

        holder.thumbImageView?.setOnClickListener {

            when (position) {

                0 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                1 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                2 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                3 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                4 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                5 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }

                6 -> {
                    Log.d("teste -> ${position}", "${position}")
                    Toast.makeText(context, "teste ${position} ", Toast.LENGTH_SHORT).show()
                }
            }

        }


    }


    override fun getItemCount(): Int = list.size


}

My Shop, Follow the code below:

/**
 * Created by faro on 9/24/17.
 */



class Shop (val name : String, val subTitle: String, val thumbnail : Int)
    
asked by anonymous 15.10.2017 / 14:06

1 answer

1

Your adapter is implemented wrong. You need something like this:

override fun getFilter(): Filter {
    return object : Filter() {
        var listShop = ArrayList<Shop>()

        override fun performFiltering(charSequence: CharSequence?): FilterResults {
            val results = Filter.FilterResults()

            if (charSequence == null || charSequence.isEmpty()) {
                results.values = baseList
                results.count = baseList.size
            } else {
                getBaseList().filterTo(listShop) { it.name.toLowerCase(Locale.getDefault()).contains(charSequence) }
                results.count = listShop.size
                results.values = listShop
            }

            return results
        }

        override fun publishResults(p0: CharSequence?, filterResults: FilterResults?) {
            setList(filterResults?.values as List<Shop>)
            notifyDataSetChanged()
        }

    }
}

fun getBaseList(): List<Shop> = baseList

fun setList(list: List<Shop>) {
    this.list = list
}
    
15.10.2017 / 17:51