Swipe To Delete From Firebase with recyclerview

82 views Asked by At

My aim was for user to swipe in recyclerview and delete element from recyclerview and firestore.For this, I used itemtouchhelper and created a callback object in the fragment. The problem is that I get the error:

java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

I am using val position=viewHolder.bindingAdapterPosition as position. And I create the document id of firebase randomly myself.

I do the document deletion as follows.The thing is that if I scroll the top element, the bottom element seems to slide along with it, but only the scroll is deleted from the firestore. Even if I scroll the bottom element, I get the error:

java.lang.IndexOutOfBoundsException: Index: 1, Size: 1

I don't understand if I'm missing the position. All I want to do is delete the element by scrolling but either the other one scrolls with it or I get an indexOutofbound error. Could you help me please?

val swipeToDeleteCallback =object : SwipeToDeleteCallback() {
    override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        val position=viewHolder.bindingAdapterPosition
        firestore.collection("Foods").document(foodList[position].docId).delete()
             .addOnSuccessListener {
                   foodList.removeAt(position)
                   feedAdapter.notifyItemRemoved(position)
                   Toast.makeText(requireContext(),"Deleted",Toast.LENGTH_LONG).show()
              }
              .addOnFailureListener {
                   Toast.makeText(requireContext(),it.localizedMessage,Toast.LENGTH_LONG).show()
              }

    }
}

val itemTouchHelper =ItemTouchHelper(swipeToDeleteCallback)
itemTouchHelper.attachToRecyclerView(binding.recyclerView)

abstract class SwipeToDeleteCallback : ItemTouchHelper.Callback() {
  
    override fun getMovementFlags(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder
    ): Int {
        val swipeFlag=ItemTouchHelper.LEFT
        return makeMovementFlags(0,swipeFlag)
    }

    override fun onMove(
        recyclerView: RecyclerView,
        viewHolder: RecyclerView.ViewHolder,
        target: RecyclerView.ViewHolder
    ): Boolean {
        return false
    }

}
0

There are 0 answers