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

如何从Firebase Realtime Database中获取自动生成的PushKey

解决方案

你之前调用reference.ref.key获取的是整个Users根节点的引用对应的标识,自然拿不到子节点的PushKey。你只需要在遍历查询到的子节点时,直接取每个userSnapshot的key属性即可,该属性返回的就是你生成的PushKey。

修正后的代码示例

var query = reference.orderByChild("nik").equalTo(induk)
query.addListenerForSingleValueEvent(object : ValueEventListener {
    @SuppressLint("SetTextI18n")
    override fun onDataChange(dataSnapshot: DataSnapshot) {
        if (dataSnapshot.exists()) {
            for (userSnapshot in dataSnapshot.children) {
                // 直接取当前匹配节点的key就是目标PushKey
                val targetPushKey = userSnapshot.key
                println(targetPushKey) // 输出类似 -MZxHIafETe10OiOuR2J 的结果
                
                // 后续业务逻辑可在此处编写
                // val userData = userSnapshot.getValue(YourUserClass::class.java)
            }
        }
    }

    override fun onCancelled(error: DatabaseError) {
        // 按需补充查询取消的异常处理逻辑
        Log.w("FirebaseQuery", "loadUser:onCancelled", error.toException())
    }
})

原理说明

  • Firebase Realtime Database返回的DataSnapshot实例,key属性始终对应当前快照节点在父节点下的命名标识
  • 你通过orderByChild查询返回的dataSnapshot是包含所有匹配结果的集合,遍历每个子快照时,子快照的key就是你调用push()生成的唯一随机PushKey

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 01:24:02