I am beginning to learn Cloud Firestore using the Firebase SDK on Android, and I have run into an issue where I retrieve data from the Firestore database through an OnCompleteLi
The variable isn't "going back" to null. The issue is that the listener you added is being invoked some unknown amount of time after the query finishes. You don't know how long it's going to take. Because the time is unknown, the a Task is returned immediately by get()
, and the callbacks you attach to it will be invoked some time later. Since get()
returns immediately, the variable sport
will retain its individual value of null until the callback is invoked. This means that you should only use the results from within the callback. Or, if you want to store it somewhere, only access it when you are sure the callback has been invoked.
In fact, all Firebase APIs are asynchronous. Read this to learn why. You should become familiar with asynchronous programming in order to use Firebase SDKs.
For Android specifically, you should learn how the Play Services Task API works.