0

我在我的 android 应用程序中使用 firestore。

在下面的代码中,我可以期望异常为非空吗?

FirebaseFirestore.getInstance().collection("items").document("abc").get().addOnCompleteListener(task -> {
    if (!task.isSuccessful()) {
        Exception e = task.getException();
        //Can I expect e to be non null, or do I have to check for null?
    }
});
4

2 回答 2

2

如果您使用 OnCompleteListener,则保证有结果或异常。如果task.isSuccessful(),则保证您有一个结果对象,并且没有例外。

addOnCompleteListener(task -> {
    if (!task.isSuccessful()) {
        // Exception is guaranteed to be non-null
        Exception e = task.getException();
    }
    else {
        // Result is guaranteed to be non-null
        task.getResult();
    }
});

如果使用 an OnSuccessListener,则结果保证为非空,但如果出现错误则不会被调用。

如果使用 an OnFailureListener,则异常保证为非空,但如果没有错误,则不会调用它。

如果您不想在 a 中检查是否成功,可以链接 anOnSuccessListener和a 。OnFailureListenerOnCompleteListener

您可以在此博客系列中阅读我对 Tasks 的规范参考。

于 2019-03-24T16:24:30.677 回答
1

根据 OnComplete 方法中的任务文档,是的,它必须不为空。

返回导致任务失败的异常。如果任务尚未完成或成功完成,则返回 null。链接 - https://developers.google.com/android/reference/com/google/android/gms/tasks/Task.html#getException()

于 2019-03-24T08:01:59.237 回答