'When deleting text from TextInputEditText - RecyclerView item positions are not updated android
i have a fragment with a RecyclerView and TextInputEditText (for searching through Firebase Database)
When I start writing some text to filter the RecyclerView, I get the correct result, however if I remove text from TextInputEditText, the positions of the elements are not updated. For example: I have a RecyclerView of 3 elements, I filter by name and RecyclerView shows me only the third element, then I delete all the text with the TextInputEditText, all elements are returned, but my third element has the position of the first element. How can i fix this problem?
My code and video below:
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
setupPlacesAdapter()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FirebaseApp.initializeApp(requireContext())
getPlaces()
binding.searchBar.addTextChangedListener(object: TextWatcher {
override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, size: Int) {
val query = binding.searchBar.text.toString().uppercase()
if (query.isEmpty()) {
getPlaces()
} else {
filterByName(query)
}
}
})
}
private fun setupPlacesAdapter() {
placeAdapter = PlaceAdapter()
binding.rvPlaces.layoutManager = LinearLayoutManager(
requireContext(),
LinearLayoutManager.HORIZONTAL,
false
)
binding.rvPlaces.adapter = placeAdapter
}
private fun getPlaces() {
val reference = FirebaseDatabase.getInstance().getReference("Places")
reference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val list = ArrayList<Place>()
for (placeSnapshot in snapshot.children) {
val place = placeSnapshot.getValue(Place::class.java)
list.add(place!!)
}
placeAdapter.submitList(list)
placeAdapter.notifyDataSetChanged()
}
}
})
}
private fun filterByName(query: String) {
Log.d("MyTag", "Filtered")
val reference = FirebaseDatabase.getInstance()
.getReference("Places")
.orderByChild("name")
.startAt(query)
.endAt(query + "\uf8ff")
reference.addValueEventListener(object: ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
val list = ArrayList<Place>()
for (placeSnapshot in snapshot.children) {
val place = placeSnapshot.getValue(Place::class.java)
list.add(place!!)
}
placeAdapter.submitList(list)
placeAdapter.notifyDataSetChanged()
}
}
})
}
Demonstration of the problem itself on the video at the link: https://youtu.be/YlD9LTppC0s
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
