[英]How to delete selected item node from firebase realtime database?
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.
帮我解决这个问题。
Every time you call push()
it generates a new unique ID, which won't exist in the database yet.每次调用
push()
时,它都会生成一个新的唯一 ID,该 ID 尚不存在于数据库中。 So in this code, you generate such a new unique ID in placeId
and then try to delete the non-existing node:所以在这段代码中,你在
placeId
中生成了这样一个新的唯一 ID,然后尝试删除不存在的节点:
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.由于
placeId
处的节点从不存在,因此对removeValue()
的调用无效。
If you want to know an existing place, you'll need to know its key and pass that to the delete call.如果你想知道一个现有的地方,你需要知道它的键并将其传递给 delete 调用。 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.