Here is the code that I am trying for removing the particular node of data from the realtime database.
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val place = mPlaces[position]
holder.place.text = place.getPlace()
holder.deletePlace.setOnClickListener {
val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
val placeRef = FirebaseDatabase.getInstance().reference
val placeId = placeRef.child("UserPlaces").child(currentUserID).push().key
if (placeId != null) {
placeRef.child("UserPlaces").child(currentUserID).child(placeId).removeValue()
}
}
}
this is the snippet of the realtime database
"UserPlaces": {
"6yM7mtdJs1NPBCF3Je5hUpOA4h44": {
"-NHMwCmm4-C2hBCdrbe2": {
"place": "kjdlafaslfjlf",
"placeType": "lsjaffaljs"
}
}
},
I am unable to delete the data from realtime database. I refered this link to solve the problem but I am unable to do it. Help me in solving this problem.
CodePudding user response:
Every time you call push()
it generates a new unique ID, which won't exist in the database yet. So in this code, you generate such a new unique ID in placeId
and then try to delete the non-existing node:
val placeId = placeRef.child("UserPlaces").child(currentUserID).push().key
if (placeId != null) {
placeRef.child("UserPlaces").child(currentUserID).child(placeId).removeValue()
}
Since the node at placeId
never exists, the call to removeValue()
has no effect.
If you want to know an existing place, you'll need to know its key and pass that to the delete call. This can commonly be done because you read the data from the database to show it in your app and then kept the key in a variable/list (most common). Alternatively, you may know some other attribute of the node you want to delete, and can then use a query to find the corresponding key.
If you don't know the key, nor have any way to determine it through a query, the only option is to delete all places for the user, which you'd do with:
placeRef.child("UserPlaces").child(currentUserID).removeValue()