How to Return a Documentsnapshot as a Result of a Method

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



Leave a reply



Submit