I have a recyclerView that users can add or delete item rows and that rows saving the Firebase Firestore. Adding function works fine but deleting function does not. I created an interface (Listener) through PairDetailRecyclerAdapter
. It contains DeleteOnClick
method which have myList and position parameters. Also I have a deleteData
method through my viewModel for deleting documents from Firestore. When i clicked the delete button on Firebase side everything is OK but on recyclerView side items duplicating themselves or shuffling
Here is the codes:
Interface and onClickListener from PairDetailRecyclerAdapter
:
interface Listener {
fun DeleteOnClick(list: ArrayList<AnalyzeDTO>, position: Int)
}
override fun onBindViewHolder(holder: AnalyzeViewHolder, position: Int) {
holder.itemView.rrRatioText.text = "RR Ratio: ${list[position].rrRatio}"
holder.itemView.resultText.text = "Result: ${list[position].result}"
holder.itemView.causeForEntryText.text = "Reason: ${list[position].reason}"
holder.itemView.conceptText2.text = "Concept: ${list[position].concept}"
if (list[position].tradingViewUrl != null && list[position].tradingViewUrl!!.isNotEmpty()) {
Picasso.get().load(list[position].tradingViewUrl)
.into(holder.itemView.tradingviewImage);
}
holder.itemView.imageView.setOnClickListener {
listener.DeleteOnClick(list, holder.layoutPosition)
}
deleteData from ViewModel :
fun deleteData(position: Int) {
var chosenPair = ozelSharedPreferences.clickiAl().toString()
val currentU = Firebase.auth.currentUser
val dbCollection = currentU?.let {
it.email.toString()
}
database.collection(dbCollection!!).document("Specified").collection("Pairs")
.document(chosenPair).collection("Analysis").get().addOnSuccessListener { result ->
val newList = ArrayList<String>()
if (result != null) {
for (document in result) {
newList.add(document.id)
database.collection(dbCollection!!).document("Specified").collection("Pairs")
.document(chosenPair).collection("Analysis").document(newList[position]).delete()
}
}
}
}
Overrided Listener in PairDetailActivity
override fun DeleteOnClick(list: ArrayList<AnalyzeDTO>, position: Int) {
viewModel.deleteData(position)
list.removeAt(position)
recyclerA.notifyItemRemoved(position)
}
// this code works for me in fact, it would be better if you did it as a model and it would be suitable for mvvm architecture.