How to return a DocumentSnapShot as a result of a method?
Is it possible to return Firestore data from a function?
There's one important thing you'll need to know:
All Firestore APIs are asynchronous. They return immediately, and you must use the callback to get the results. There is no guarantee when the callback will be invoked, and it must be handled asynchronously. Your getCity()
function will not be able to return an object immediately.
get()
returns a Task object (provided by the Play services Task API) that represents the asynchronous query. If you want to await()
the result of that, your easiest route is to use the kotlinx-coroutines-play-services library to convert that task into a suspend fun
that can be awaited. If you do this, your getCity()
should also be a suspend fun
so that it can deliver the result asynchronously to its caller.
See also: How to use kotlin coroutines in firebase database
Can't get Firestore to return a field value from a collection in Android Studio
Any code that needs to have access to the data from the database, has to be inside the completion listener that gets called when that data is available.
So:
docRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
@Override
public void onComplete(@NonNull Task<DocumentSnapshot> task) {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
String dbValue = document.getString("password");
tvMenu.setText(dbValue); // br> } else {
Log.d("TAG", "No such document");
}
} else {
Log.d("TAG", "get failed with ", task.getException());
}
}
});
For more on this, see:
- How to check a certain data already exists in firestore or not
- Why does my function that calls an API or launches a coroutine return an empty or null value?
- How to return a DocumentSnapShot as a result of a method?
- getContactsFromFirebase() method return an empty list
- Setting Singleton property value in Firebase Listener
Related Topics
Why Is It Considered a Bad Practice to Omit Curly Braces
Java.Lang.Classnotfoundexception: Didn't Find Class on Path: Dexpathlist
How to Simulate the C++ 'Friend' Concept in Java
Are There C++ Equivalents For the Protocol Buffers Delimited I/O Functions in Java
C++ Equivalent of Java'S Instanceof
How to Round Up the Result of Integer Division
Access Private Field of Another Object in Same Class
How to Access the Java Method in a C++ Application
Is Short Circuit Evaluation Guaranteed in C++ as It Is in Java
How to Create Recyclerview With Multiple View Types
How to Add a Timestamp in Firestore With Android
How to Change the Decimal Separator of Decimalformat from Comma to Dot/Point
How to Stop Repeated Keypressed()/Keyreleased() Events in Swing
Java String to Date Conversion