I have a Snackbar which is being opened when a user swipes on a RecyclerView element to delete it. And this Snackbar allows a user to undo his action. I know how to get an element of the RecyclerView back. But I also have a database(SQLite). It seems to me, the best way to do a removal from a detabase is to do it when I understand that a user doesn't press "undo". Otherwise I will need to make a removal and then adding.
I want to do something sort of this:
when (snackbar_button){
was_pressed -> adapter.restoreItem(cachedPosition, cachedItem)
was_not_pressed -> dbManager.removeItem(listArray[pos].id.toString())
}
This is my code on MainActivity:
val onSwipe = object : OnSwipe(this) {
override fun onSwiped(viewHolder: ViewHolder, direction: Int) {
val cachedPosition = viewHolder.absoluteAdapterPosition
val cachedItem = adapter.listArray[cachedPosition]
when (direction) {
ItemTouchHelper.RIGHT -> {
adapter.removeItem(cachedPosition)
Snackbar.make(binding.rv, "Deleted", Snackbar.LENGTH_SHORT)
.apply {
setAction("Undo") {
adapter.restoreItem(cachedPosition, cachedItem)
}
show()
}
}
}
}
}
My adapter:
fun removeItem(pos: Int) {
listArray.removeAt(pos)
notifyItemRemoved(pos)
}
fun restoreItem(pos: Int, listMain: ListItem) {
listArray.add(pos, listMain)
notifyItemInserted(pos)
}
My code in DB to delete:
fun removeItem(_id: String) {
val id = BaseColumns._ID + "=$_id"