S
S
sanke462017-11-22 22:51:13
Android
sanke46, 2017-11-22 22:51:13

Prints zero when it's not real, why [Kotlin]?

How to output to console sumAllvalue, count outside of addValueEventListener ?

fun allDeviceLike() {
        var count : Int = 0
        var sumAllvalue : Int = 0

        mDeviceLikesRef.addValueEventListener(object : ValueEventListener{
            override fun onCancelled(p0: DatabaseError?) {
                TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
            }

            override fun onDataChange(dataSnapshot: DataSnapshot?) {
                for (child : DataSnapshot in dataSnapshot?.children!!) {
                    var objectMap : Map<String, Any>
                    objectMap = child.value as Map<String, Any>;

                    for(entary in objectMap) {
                        if(entary.key.equals("value")) {
                            count++
                            sumAllvalue += entary.value.toString().toInt()
                        }
                    }
                }

                println(sumAllvalue) // 9 [3 + 5 + 1]
                println(count) // 3 [1 + 1 + 1]
            }
        })

        println(sumAllvalue) // 0
        println(count) // 0
    }

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mikhail Chvarkov, 2017-11-23
@sanke46

The problem is most likely that onDataChange() is called later than when you are trying to print the values ​​to the console. That is, by the time

println(sumAllvalue) // 0
println(count) // 0

you have not received the dataSnapshot yet and the data has not been updated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question