FirebaseDatabase onChildChanged返回多个快照

时间:2019-11-19 14:17:05

标签: android firebase firebase-realtime-database

我有一个问题,我不能只得到最近添加的孩子。

这是我的数据库:

这是我的测试代码:

val db = FirebaseDatabase.getInstance().reference
        val newref = db.child("/Orders/ODbPagPuDFgGhj0l73lynD4Wdkr2/")


        newref.addChildEventListener(object: ChildEventListener {
            override fun onChildChanged(snap: DataSnapshot, p1: String?) {
                Log.d("ac1234","${snap}")
            }


            override fun onCancelled(p0: DatabaseError) {           }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {            }


            override fun onChildAdded(p0: DataSnapshot, p1: String?) {  }

            override fun onChildRemoved(p0: DataSnapshot) {  }

        })

这是logcat:

2019-11-19 06:02:24.596 14991-14991/com.example.fru_vegetablesadmin D/ac1234: DataSnapshot { key = -Lu2y9uay-7G3gtFI4g3, value = {locationLat=33.95212290629996, locationLong=35.62042236328125, phoneNumber=+19823737, totalPrice=8,197 L.L., optionalAddress=, optionalNote=, time=19/10/2019 16:2 , order={Fresh Cucumber={totalQuantity=3 Kg, totalPrice=7497}}} }
2019-11-19 06:02:24.603 14991-14991/com.example.fru_vegetablesadmin D/ac1234: DataSnapshot { key = -Lu2y9uay-7G3gtFI4g3, value = {locationLat=33.95212290629996, locationLong=35.62042236328125, phoneNumber=+19823737, totalPrice=8,197 L.L., optionalAddress=, optionalNote=, time=19/10/2019 16:2 , order={Fresh Cucumber={totalQuantity=3 Kg, totalPrice=7497}}} }
2019-11-19 06:02:24.645 14991-14991/com.example.fru_vegetablesadmin D/ac1234: DataSnapshot { key = -Lu2y9uay-7G3gtFI4g3, value = {locationLat=33.95212290629996, locationLong=35.62042236328125, phoneNumber=+19823737, totalPrice=8,197 L.L., optionalAddress=, optionalNote=, time=19/10/2019 16:2 , order={Fresh Cucumber={totalQuantity=3 Kg, totalPrice=7497}, Fresh Eggplant={totalQuantity=200 G, totalPrice=700}}} }

我不知道为什么它要返回3行数据,我只想听是否在uid(“ ODbPagPuD ...”)下添加了一个孩子

预先感谢

1 个答案:

答案 0 :(得分:1)

更改此:

        newref.addChildEventListener(object: ChildEventListener {
            override fun onChildChanged(snap: DataSnapshot, p1: String?) {
                Log.d("ac1234","${snap}")
            }


            override fun onCancelled(p0: DatabaseError) {           }

            override fun onChildMoved(p0: DataSnapshot, p1: String?) {            }


            override fun onChildAdded(p0: DataSnapshot, p1: String?) {  }

            override fun onChildRemoved(p0: DataSnapshot) {  }

        })

对此:

newref.addValueEventListener(object: ValueEventListener {
 override fun onDataChange(dataSnapshot: DataSnapshot) {
        Log.d("ac1234","${dataSnapshot}")

    }

    override fun onCancelled(databaseError: DatabaseError) {
        Log.w(TAG, "loadPost:onCancelled", databaseError.toException())

    }
}