0

I just started to use kotlin and room database, in my fragment i have a RecyclerView and an EditText which i would use as search for the RecyclerView. The RecyclerView's adapter is inside my ViewModel observable and i've actually set a TextWatcher to my EditText but as the data of the RecyclerView comes from my room DataBase how should i set that filtering?

When the EditText is empty i should return items from the LiveData observable..

Here is my Fragment code:

private lateinit var recyclerView: RecyclerView
private lateinit var txtSearch: EditText
private val articoliViewModel: ArticoliViewModel
    get() = (activity as MainActivity).articoliViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.recyclerView)
    txtSearch = view.findViewById(R.id.txtSearch)

    val adapter = ArticoliListAdapter()
    recyclerView.adapter = adapter
    recyclerView.layoutManager = LinearLayoutManager(activity)

    articoliViewModel.articoli.observe(viewLifecycleOwner) { articoli ->
        // Update the cached copy of the words in the adapter.
        articoli.let { adapter.submitList(it) }
    }

    txtSearch.addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {

        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

        }
    })

}
NiceToMytyuk
  • 3,644
  • 3
  • 39
  • 100
  • First decide weather you want to filter current list or you want to filter from the database(If there a pagination involved) . For first u can use Filterable like [This](https://stackoverflow.com/a/65068448/4168607) . Second option is more straightforward you just have query the DB again with the search String. – ADM Jan 20 '21 at 08:15
  • @ADM there is no pagination, and idk what would be better if filter by DB query or by List, i would use something less expansive for the performance – NiceToMytyuk Jan 20 '21 at 08:17
  • 1
    Then just Use `Filterable` i have added a link above u can find similar answers which make sense to you . – ADM Jan 20 '21 at 08:20
  • try a similar approach https://stackoverflow.com/a/65635201/11034109 – Sekiro Jan 20 '21 at 08:24

0 Answers0