代码之家  ›  专栏  ›  技术社区  ›  ahmed sabah sabri

如何从firebase实时数据库中检索最后一个值

  •  1
  • ahmed sabah sabri  · 技术社区  · 2 年前

    我有一个arduino,它可以将读数推送到数据库中,我还有一个android应用程序,可以检索读数并在textView中显示。

    enter image description here

    我的应用程序不断获取文本视图中的所有键和值。

    我如何解决这个问题并只显示最后一个值?

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        // Initialize Firebase App
        FirebaseApp.initializeApp(this)
    
        // Inflate layout
        Binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(R.layout.activity_landing)
    
        // Initialize Firebase Database query
        val query = FirebaseDatabase.getInstance("https://voltageread-22aa9-default-rtdb.firebaseio.com/")
            .reference
            .orderByKey()
            .limitToLast(1)
    
        // Fetch data from Firebase Realtime Database and save it in a variable
        query.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if (snapshot.exists() && snapshot.value != null) {
                    val lastChildSnapshot = snapshot.children.lastOrNull()
                    if (lastChildSnapshot != null) {
                        val data = lastChildSnapshot.value.toString()
                        if (!data.isNullOrEmpty()) {
                            Log.d("Firebase", "Data received: $data ")
                            // Update the UI with the received data
                            Binding.voltage.text = data.substringAfter('=')
                        }
                    }
                }
            }
    
            override fun onCancelled(error: DatabaseError) {
                Log.e("Firebase", "Data fetching cancelled: ${error.message}  ")
            }
        })
    

    试着使用内置的功能,但似乎什么都不起作用

    1 回复  |  直到 2 年前
        1
  •  0
  •   Frank van Puffelen    2 年前

    当您使用诸如 orderByKey limitToLast 在Firebase中,它们对您引用的数据库中路径的直接子节点进行操作。由于您在数据库的根上进行操作,因此会对其下的密钥进行排序和筛选,只剩下一个子密钥: all

    您要做的是对 全部的 路径本身,以便Firebase对 -N... 下面有子节点。在代码中:

    val query = FirebaseDatabase.getInstance("https://voltageread-22aa9-default-rtdb.firebaseio.com/")
        .reference
        .child("all") // 👈
        .orderByKey()
        .limitToLast(1)
    
    推荐文章