Answer the question
In order to leave comments, you need to log in
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
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question