'update recyclerview in real time after firebase delete
I have an app with recyclerview with the option to edit and delete the items from the list. when I delete or update one of the items it gets updated or deleted successfully from the realtime database in firebase but for some reason, in the recyclerview it duplicates the item and I need to rest the activity in order to see the change currently. that is unless there is only one item in the list then it works as expected.
the activity to show the recylerview:
private lateinit var dbref: DatabaseReference
private lateinit var userRecyclerView: RecyclerView
private lateinit var userArrayList: ArrayList<User>
private fun getUserData(){
dbref = FirebaseDatabase.getInstance().getReference("Users")
dbref.addValueEventListener(object :ValueEventListener{
override fun onDataChange(snapshot: DataSnapshot) {
if(snapshot.exists()){
for(userSnapshot in snapshot.children){
val user = userSnapshot.getValue(User::class.java)
userArrayList.add(user!!)
}
userRecyclerView.adapter = MyAdapter(userArrayList)
}
}
override fun onCancelled(error: DatabaseError) {
}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
userRecyclerView = findViewById(R.id.userlist)
userRecyclerView.layoutManager = LinearLayoutManager(this)
userRecyclerView.setHasFixedSize(false)
userArrayList = arrayListOf<User>()
getUserData()
onBindViewHolder:
override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
val currentUser = userList[position]
holder.username.text = currentUser.name
holder.app.text = currentUser.app
holder.password.text = currentUser.password
delete:
holder.delete.setOnClickListener(){
val builder = AlertDialog.Builder(holder.itemView.context)
builder.setMessage("Are you sure you want to Delete?")
.setCancelable(false)
.setPositiveButton("Yes") { _, _ ->
// Delete from firebase
val db = FirebaseDatabase.getInstance()
val ref = db.getReference("Users")
ref.child(currentUser.id.toString()).removeValue().addOnCompleteListener(){
userList.removeAt(position)
notifyItemRemoved(position)
}
}
.setNegativeButton("No") { dialog, _ ->
// Dismiss the dialog
dialog.dismiss()
}
val alert = builder.create()
alert.show()
}
update:
val user = mapOf(
"app" to holder.app.text.toString(),
"name" to holder.username.text.toString(),
"password" to holder.password.text.toString()
)
val db = FirebaseDatabase.getInstance()
val ref = db.getReference("Users")
ref.child(currentUser.id.toString()).updateChildren(user).addOnSuccessListener(){
notifyItemChanged(position)
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
