Search code examples
androidfirebaselisteneronstart

Firebase Code Running After Everything Else


I'm making an Android app with Firebase and within one of my activities I need to read data from Firebase before doing anything else. To do so, I'm using a ValueEventListener. The problem is, Android is running the rest of the code first and then it gets the result/runs the code within the listener's onDataChange() method. I know this because I debugged using Logs and indeed the result arrives a couple of seconds after the rest of the code runs.

I've seen examples of people writing the code you want to run after the query within another method, and then calling that method inside the onDataChange(). I tried doing that, also tried moving the listener to another class and calling the method and even tried controlling the flow of the code with variables, nothing worked. Any ideas of what can I do?

Btw, I don't know if this affects in any way of not but, my piece of code that depends on Firebase's result is inside the onStart() method, so I suppose Android would always run the onStart() first and then get the result from the listener.

Thanks!


Solution

  • The ValueEventListeners are asynchronous, so they won't run first. Instead, try calling a function that does what you wanted to do with the listener from inside the onDataChange() function.