0

I am retrieving the data from Firebase Database and I am able to successfully get it, yet when I create a variable in my function to return it returns null, evens though when I debug I can see that I have retrieved the data on Datasnapshot, yet the placesList array when its returned is null! I am using MVVM architecture, and cant get why the function doesn't return the value while its being read inside the onDataChange lampda!

Here is my code

    fun getAllPlacesFromFireBase(): ArrayList<Place>  {
    var placesList : ArrayList<Place> = ArrayList()

    firebaseDatabase.child("Best Locations").addValueEventListener(object : ValueEventListener{
        override fun onDataChange(snapshot: DataSnapshot) {
            if (snapshot.exists()){
                for (placesSnapShot in snapshot.children){
                    val place = placesSnapShot.getValue(Place::class.java)
                    placesList.add(place!!)
                }
            }
        }

        override fun onCancelled(error: DatabaseError) {
            Log.e("Reprository",error.toString() )
        }

    })
    return placesList
}

when I debug I can see that the value is read and added in placesList.add(place!!) still, when I return the places list in the end of the function I see it's null and it didn't get any of the value at all. can someone help me how to solve this, as I have converted to kotlin recently and this was how I e exactly get the data in Java

Ahmed Rabee
  • 185
  • 14
  • 1
    Data is loaded from Firebase (and most cloud APIs) asynchronously, to prevent blocking the user from using the app. Your main code will continue to run straight way, which is why `return placesList` returns the empty value you set when you create the variable. Then when the data is available your `onDataChange` gets executed and calls `placesList.add(place!!)`, but nobody will know that happened anymore. For this reason, any code that needs the data from the database needs to be inside `onDataChange`, be called from there, or otherwise synchronized. – Frank van Puffelen Feb 27 '22 at 17:16
  • 1
    [This question covers this too](https://stackoverflow.com/questions/57330766/why-does-my-function-that-calls-an-api-return-an-empty-or-null-value) – Tyler V Feb 27 '22 at 17:21
  • You might also be interested in reading this article, [How to read data from Firebase Realtime Database using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5). – Alex Mamo Feb 28 '22 at 09:57
  • I have solved this using a callback, as I figured out the function return before the operation of firebase is done as it work asynchronously, so using a callback interface solved this issue – Ahmed Rabee Mar 01 '22 at 21:36

0 Answers0