Firebase & retrieving elements

I am trying to read x the number of elements from Firebase, but I have a feeling that I do not understand something ...

The DataSnapshot returns the correct child count, however, when I try to execute a loop through children, the loop never executes.

Note: Code in Kotlin

fun list(count: Int, callback: ListCallback) {
    val playersRef = firebase.child("players")
    val queryRef = playersRef.orderByChild("rank").limitToFirst(count)
    queryRef.addListenerForSingleValueEvent(object : ValueEventListener {

        override fun onCancelled(error: FirebaseError?) {
            Log.e("firebase", error!!.message)
        }

        override fun onDataChange(snapshot: DataSnapshot?) {
            val children = snapshot!!.children
            // This returns the correct child count...
            Log.i("firebase", children.count().toString())
            val list = ArrayList<Entry>()
            // However, this loop never executes
            children.forEach {
                val e = Entry()
                e.name = it.child("name").value as String
                e.rank = it.child("rank").value as Long
                e.wins = it.child("wins").value as Long
                e.losses = it.child("losses").value as Long
                Log.i("firebase", e.toString())
                list.add(e)
            }
            callback.onList(list)
        }
    })
}
+4
source share
1 answer

This works for me:

val firebase: Firebase = Firebase("https://stackoverflow.firebaseio.com/34378547")

fun main(args: Array<String>) {
    list(3)
    Thread.sleep(5000)
}

fun list(count: Int) {
    val playersRef = firebase.child("players")
    val queryRef = playersRef.orderByChild("rank").limitToFirst(count)
    queryRef.addListenerForSingleValueEvent(object : ValueEventListener {

        override fun onCancelled(error: FirebaseError?) {
            println(error!!.message)
        }

        override fun onDataChange(snapshot: DataSnapshot?) {
            val children = snapshot!!.children
            // This returns the correct child count...
            println("count: "+snapshot.children.count().toString())
            children.forEach {
                println(it.toString())
            }
        }
    })
}

Exit:

count: 2
DataSnapshot { key = -K6-Zs5P1FJLk4zSgNZn, value = {wins=13, name=fluxi, rank=1, losses=1} }
DataSnapshot { key = -K6-ZtdotHkkBzs5on9X, value = {wins=10, name=puf, rank=2, losses=42} }

Update

The comments discussed why it works snapshot.children.count(), but children.count()not. The problem is caused by two facts:

  • Firebase DataSnapshot.getChildren()returns Iterable, which can only be renamed forward (like a contract Iterable).
  • Kotlin count() Iterable .

, Kotlin count(), Iterable . for . snapshot.children , , .

, Kotlin count(), Firebase childrenCount:

println("count: "+snapshot.childrenCount)
+3

Source: https://habr.com/ru/post/1620955/


All Articles