I am trying to get data from firebase (once) so I am using the OnCompleteListener but it seems it is not being triggered
private void checkAvailability() {
db = FirebaseFirestore.getInstance();
String datePath = "Date " + reservationObject.getDate();
String timePath = "Time " + reservationObject.getTime();
docRef = db.collection(datePath).document(timePath);
docRef.get().addOnCompleteListener(task -> {
if (task.isSuccessful()) {
DocumentSnapshot document = task.getResult();
if (document.exists()) {
//function logic//
} else {
task.getException();
}
}
});
} // skipping immediately to this line
this is the gardle dependency file:
implementation(platform("com.google.firebase:firebase-bom:32.7.0"))
implementation("androidx.appcompat:appcompat:1.6.1")
implementation("com.google.android.material:material:1.10.0")
implementation("androidx.constraintlayout:constraintlayout:2.1.4")
implementation("androidx.navigation:navigation-fragment:2.7.6")
implementation("androidx.navigation:navigation-ui:2.7.6")
implementation("com.google.firebase:firebase-database:20.3.0")
implementation("com.google.firebase:firebase-firestore:24.10.0")
testImplementation("junit:junit:4.13.2")
androidTestImplementation("androidx.test.ext:junit:1.1.5")
androidTestImplementation("androidx.test.espresso:espresso-core:3.5.1")
implementation ("com.google.firebase:firebase-messaging:15.0.2")```
and this is the firebase collection:
Tried getting the task.getException(); but the block is completely ignored
2
Answers
I changed database to realtime (instead of firestore) and used this answer: Wait Firebase async retrieve data in Android
addOnCompleteListener
receives a callback as part of it’s asynchronous behavior, it will trigger the callback once the operation has been completed.I noticed your function is synchronous, which means it simply continues to execute and the flow might end before your async operation has been completed.
As I see it, you could either –
Future
of some sort