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