0

I've a function like below, trying to read data from Firebase DB, counting them and finally return the count number.

But "ad_count" value is always 0. Somehow I can't pass the data from "onDataChange". How can I do that? Thanks.

 fun count():Int{

        var ad_count :Int = 0
        var ref = FirebaseDatabase.getInstance().reference

        var query =ref.child("users")
            .child(FirebaseAuth.getInstance().currentUser!!.uid)

        query.addListenerForSingleValueEvent(object : ValueEventListener{
            override fun onCancelled(p0: DatabaseError) {
            }
            override fun onDataChange(p0: DataSnapshot) {
                var array : ArrayList<String> = ArrayList()

                for (i in p0.children){

                    if(i?.key.toString().startsWith("ads",false)){
                        array.add(i?.key.toString())
                    }
                }

                 ad_count = array.size +1
                 //return ad_count -> if I use in here, throwing "type mismatch" error.
            }
        })

        return ad_count   //it's always return 0 here
    }
sleepy
  • 167
  • 1
  • 2
  • 9
  • 1
    you will want to look into callbacks, for reference take a peek at [callbacks in kotlin](https://stackoverflow.com/questions/51042961/how-does-firebase-completion-callbacks-work-in-kotlin). the reason ad_count is always zero is, think about what's going on, your client (kotlin app) is requesting data from the server (firebase), kotlin continues to process, hence, ad_count isn't updated and remains it's original value. in other words, asynchronous calls to firebase don't sync properly without "interrupting" them appropriately, hence callbacks. – EvOlaNdLuPiZ Dec 25 '19 at 04:35
  • I'm new at Kotlin and I don't know anything about callbacks. Let me check. – sleepy Dec 25 '19 at 04:44
  • 1
    Data is loaded from Firebase asynchronously. Your main code continues, and then when the data is available, your `onDataChange` is called. This means that by the time your `return ad_count` runs, the `ad_count = array.size +1` hasn't run yet. Any code that needs data from the database must be inside `onDataChange` or be called from there. See for a longer explanation my answer to https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 – Frank van Puffelen Dec 25 '19 at 04:49
  • Thanks for the information @Frank, I'll check the link. – sleepy Dec 25 '19 at 05:06
  • @Frank I couldn't solve how to read data from the interface. (https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method). readData is java code, I couldn't convert to Kotlin. Should I open another topic? – sleepy Dec 26 '19 at 21:58
  • Translating that Java code to Kotlin should be fairly one on one. If you're having trouble with it, I recommend using an online converter tool or the one built into Android Studio. If you're still having problems **after** that, indeed open a new question with the [minimal, complete/standalone code that anyone can run to reproduce the problem](http://stackoverflow.com/help/mcve). – Frank van Puffelen Dec 27 '19 at 01:21
  • 1
    I added Kotlin samples (based on this [online conversion tool](https://try.kotlinlang.org/#/Kotlin%20Koans/Introduction/Java%20to%20Kotlin%20conversion/Task.kt)) to the answer I referred to earlier: https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519. – Frank van Puffelen Dec 27 '19 at 01:28

0 Answers0