You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Firebase实时数据库删除选中节点?代码执行失败求助

Firebase实时数据库删除节点失败问题解决

你的代码无法删除数据的核心原因是:你用push().key生成了一个全新的随机节点ID,而不是获取当前要删除的那个节点的已有ID,相当于在尝试删除一个根本不存在的路径,自然没有效果。

修正步骤:

  1. 给数据类添加节点ID字段
    确保你的Place数据类能存储数据库节点的ID(也就是类似-NHMwCmm4-C2hBCdrbe2的随机key):

    data class Place(
        val place: String? = null,
        val placeType: String? = null,
        val id: String? = null // 新增字段存储节点ID
    )
    
  2. 读取数据时保存节点ID
    在查询数据库获取用户地点列表时,把每个节点的ID赋值给对应的Place对象:

    val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
    val userPlacesRef = FirebaseDatabase.getInstance().reference.child("UserPlaces").child(currentUserID)
    
    userPlacesRef.addValueEventListener(object : ValueEventListener {
        override fun onDataChange(snapshot: DataSnapshot) {
            val placesList = mutableListOf<Place>()
            for (childSnapshot in snapshot.children) {
                val place = childSnapshot.getValue(Place::class.java)
                place?.let {
                    it.id = childSnapshot.key // 将节点ID赋值给Place对象
                    placesList.add(it)
                }
            }
            mPlaces = placesList
            notifyDataSetChanged()
        }
    
        override fun onCancelled(error: DatabaseError) {
            // 按需处理查询失败逻辑,比如打印错误信息
            error.toException().printStackTrace()
        }
    })
    
  3. 修改删除逻辑,使用已有节点ID
    点击删除按钮时,直接用Place对象里存储的ID定位到要删除的节点:

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = mPlaces[position]
    
        holder.place.text = place.place
    
        holder.deletePlace.setOnClickListener {
            val currentUserID = FirebaseAuth.getInstance().currentUser!!.uid
            val placeId = place.id
            
            if (placeId != null) {
                FirebaseDatabase.getInstance().reference
                    .child("UserPlaces")
                    .child(currentUserID)
                    .child(placeId)
                    .removeValue()
                    .addOnSuccessListener {
                        // 删除成功后更新本地列表,刷新RecyclerView
                        mPlaces.removeAt(position)
                        notifyItemRemoved(position)
                        notifyItemRangeChanged(position, mPlaces.size)
                    }
                    .addOnFailureListener {
                        // 处理删除失败情况
                        it.printStackTrace()
                    }
            }
        }
    }
    

这样修改后,就能精准定位到你要删除的数据库节点,完成删除操作。

内容的提问来源于stack exchange,提问作者CHETAN

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 20:55:48