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

Firebase实时数据库Kotlin:按选定值查询push生成键数据问题

Firebase实时数据库查询push节点数据无响应的修复方案

你的代码核心问题是查询返回的是匹配条件的push节点集合,但你直接在根查询快照上取Time/Date字段,这会导致取不到值——因为这些字段存在于每个push生成的子节点里,而非查询返回的根快照本身。此外代码还存在字段名错误(你要获取日期却写了Details),以及类型转换的空安全隐患。

修正后的代码

val btnSyncing = findViewById<TextView>(R.id.btnSync)
btnSyncing.setOnClickListener {
    val user = FirebaseAuth.getInstance().currentUser ?: run {
        Toast.makeText(baseContext, "未登录", Toast.LENGTH_LONG).show()
        return@setOnClickListener
    }
    val userid = user.uid
    val database = FirebaseDatabase.getInstance()
    val reference = database.getReference("Profile")
    val timeTextView = findViewById<TextView>(R.id.txtTime)
    val dateTextView = findViewById<TextView>(R.id.txtDate)

    reference.child(userid)
        .child("Delivery Details")
        .orderByChild("Date")
        .equalTo("24/9/22")
        .addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                // 遍历所有匹配的push节点
                for (childSnapshot in dataSnapshot.children) {
                    // 安全获取字段值,避免空指针崩溃
                    val time = childSnapshot.child("Time").value as? String
                    val date = childSnapshot.child("Date").value as? String
                    
                    timeTextView.text = time ?: "无时间数据"
                    dateTextView.text = date ?: "无日期数据"
                    // 如果只需要第一个匹配结果,遍历后直接退出循环
                    break
                }
                // 无匹配数据时提示用户
                if (!dataSnapshot.exists()) {
                    Toast.makeText(baseContext, "未找到对应日期的配送记录", Toast.LENGTH_LONG).show()
                }
            }

            override fun onCancelled(error: DatabaseError) {
                Toast.makeText(baseContext, "查询失败: ${error.message}", Toast.LENGTH_LONG).show()
            }
        })
}

额外注意事项

  • 数据库权限检查:确保Firebase实时数据库规则允许当前用户读取对应节点,示例规则如下:
{
  "rules": {
    "Profile": {
      "$uid": {
        "Delivery Details": {
          ".read": "$uid === auth.uid",
          ".write": "$uid === auth.uid"
        }
      }
    }
  }
}
  • 日期格式优化:建议使用标准日期格式(如yyyy-MM-dd),避免后续查询排序或匹配出现异常
  • 组件规范:按钮功能更适合用Button组件实现,而非TextView

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:01:44