OnCompleteListener 块被忽略(android studio,java)

问题描述 投票:0回答:1

我正在尝试从 firebase 获取数据(一次),所以我使用 OnCompleteListener 但它似乎没有被触发

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

这是gardle依赖文件:

 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")```

这是 firebase 集合:

尝试获取task.getException();但该块完全被忽略了

java android-studio event-listener
1个回答
0
投票

addOnCompleteListener
接收回调作为其异步行为的一部分,一旦操作完成,它将触发回调。

我注意到您的函数是同步的,这意味着它只是继续执行,并且流程可能会在异步操作完成之前结束。

据我所知,你可以 -

  • 重构代码流程以使用某种
    Future
  • 同步执行调用
© www.soinside.com 2019 - 2024. All rights reserved.