It's working with initial value but not updating with searchview texts:
File Fragment
class TripHome : Fragment() {
private lateinit var mTripViewModel: TripViewModel
override fun onCreateView() {
//trimmed adapter initialize
mTripViewModel = ViewModelProvider(this).get(TripViewModel::class.java)
mTripViewModel.showTripData.observe(viewLifecycleOwner, Observer { trip ->
adapter.setData(trip)
})
view.fab_addTrip.setOnClickListener{
findNavController().navigate(R.id.action_tripHome_to_tripAdd)
}
val menuHost: MenuHost = requireActivity()
val search = menuHost.addMenuProvider(object : MenuProvider {
override fun onCreateMenu(menu: Menu, menuInflater: MenuInflater) {
// Add menu items
menuInflater.inflate(R.menu.searchtrip, menu)
val search = menu.findItem(R.id.searchItems)
val searchView = search.actionView as SearchView
searchView.isSubmitButtonEnabled = true
searchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
if (query != null) {
getItemsFromDb(query)
}
return true
}
override fun onQueryTextChange(query: String?): Boolean {
if (query != null) {
getItemsFromDb(query)
}
return true
}
})
}
override fun onMenuItemSelected(menuItem: MenuItem): Boolean {
// Handle the menu selection
return when (menuItem.itemId) {
R.id.searchItems -> {
// clearCompletedTasks()
true
}
else -> false
}
}
}, viewLifecycleOwner, Lifecycle.State.RESUMED)
return view
}
private fun getItemsFromDb(searchText: String) {
var searchText = searchText
searchText = "%$searchText%"
mTripViewModel.searchTrip(query = searchText).observe(this, Observer { trip->
trip?.let {
Log.e("List = ", trip.toString())
}
})
}
}
My list adapter file
class TripList : RecyclerView.Adapter<TripList.MyViewHolder>() {
private var tripList = emptyList<TripModel>()
//trimmed onCreateViewHolder and onBindViewHolder
fun setData(trip: List<TripModel>){
this.tripList = trip
notifyDataSetChanged()
}
}
I tested the search view and I got these detail in logcat, seem the search view worked but the view not filter
2022-11-06 21:09:05.090 9252-9252/com.example.newone E/List =: [TripModel(id=3, name=879, vehicle=qweqwe, date=12/12/4321, start=qewqe, to=sdadas, risk=fbcxvc, description=xcvsdfs)]
Can someone help me, I need the recyclerview could filter data, thank you.
CodePudding user response:
It's because you are not updating your adapter after you filter:
private fun getItemsFromDb(searchText: String) {
var searchText = searchText
searchText = "%$searchText%"
mTripViewModel.searchTrip(query = searchText).observe(this, Observer { trip->
trip?.let {
Log.e("List = ", trip.toString())
// call this method again with new trip list
adapter.setData(trip)
}
})
}