The list content in recyclerview is getting duplicated when navigating to other fragment and getting back to the fragment.
When a user clicks on item and navigate back to the same fragment the recyclerview is getting duplicated
ViewModel:
private var listMutableLiveData: MutableLiveData<ArrayList<OffersModelClass>> =
MutableLiveData()
var arrayListMainUI: ArrayList<OffersModelClass> = ArrayList()
val listLiveData: LiveData<ArrayList<OffersModelClass>>
get() = listMutableLiveData
fun loadData(reload: Boolean) {
if (reload) {
databaseReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
for (data in snapshot.children) {
val model = data.getValue(OffersModelClass::class.java)
//Getting the offer ID to load its images
val imageID: String = model?.imageID.toString()
val fileRef11 = FirebaseStorage.getInstance().reference.child(
"offers/$imageID.jpg"
)
fileRef11.downloadUrl.addOnSuccessListener { uri ->
//Assigning the image uri and converting it to string
model?.ImageUri = uri.toString()
//Assigning the new time format
model?.Time = model?.Time?.let { calculateTimeAge(it) }
//Adding the data to arraylist as whole to observe it from the fragment
arrayListMainUI.add(model as OffersModelClass)
listMutableLiveData.postValue(arrayListMainUI)
}
}
}
override fun onCancelled(error: DatabaseError) {
TODO("Not yet implemented")
}
})
}
}
Fragment:
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.setHasFixedSize(true)
viewModel = ViewModelProvider(requireActivity()).get(ViewModel::class.java)
if (user != null) {
// User is signed in
viewModel.loadData(true)
}
viewModel.listLiveData.observe(viewLifecycleOwner, { arrayList ->
offerAdapter = OfferAdapter(arrayList)
recyclerView.adapter = offerAdapter
offerAdapter.notifyDataSetChanged()
})
CodePudding user response:
Call arrayListMainUI.clear() inside onDataChanged before
for (data in snapshot.children)
. Why would this work?.
Answer: When you are navigating back to your fragment you are not creating another instance of your arrayListMainUI. So, the previous data is not being cleared and the new ones are being added with previous thus creating duplicate list.