android - 为什么 Android Studio 指示对象可能为 null,但实际上它不能为 null?

标签 android firebase android-studio google-cloud-firestore lint

这是我正在使用的代码:

ref.get().addOnCompleteListener(task -> {
    if (task.isSuccessful()) {
        DocumentSnapshot document = task.getResult();
        if (document.exists()) {
            Log.d(TAG, "DocumentSnapshot data: " + document.getData());
        }
    }
});

Android Studio 是如何突出显示错误的:

enter image description here

据我了解,answer :

A successfully completed task will never pass null for the DocumentSnapshot.

如何在不检查无效性的情况下解决这个问题?谢谢!

最佳答案

Why does Android Studio indicate that an object might be null when it cannot be?

因为 lint 无法知道。 document.exists() 通常可以返回 null,这就是您看到警告的原因。 Lint 执行基本检查,并且不了解有关 Firebase API 的详细信息。您甚至可以使用 Java Core API 重现此行为。

How can I solve this without checking for nullity? Thanks!

如果你100%确定它永远不会为空,你可以使用

@SuppressWarnings("常量条件")

但我不建议这样做,因为您不知道 Firebase API 将来是否会发生变化。也许 Firebase 的下一版本将允许 null 返回。

关于android - 为什么 Android Studio 指示对象可能为 null,但实际上它不能为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54925393/

相关文章:

android - Android Studio 可以将 ant 构建脚本转换为 gradle 构建脚本吗?

android - AudioFormat 在 android.media.AudioFormat 中不公开

java - 如何将 String 转换为 int 并使用 Comparator 进行比较

java - firebase facebook 登录时出现身份验证失败错误

angular - Observable .do() 运算符的用例 (rxjs)

ios - Firebase + Swift 在 TableView 中删除行

android - 错误 :Cause: org. gradle.api.Project.getPluginManager()Lorg/gradle/api/plugins/PluginManager;有关更多详细信息,请参阅 IDE 日志(帮助 | 显示日志)

Libgdx 上的通用补间引擎缺少 Android Studio 'Add as Library'

java - 渲染时出现异常 : com. android.layoutlib.bridge.MockView cannot be cast to android.view.ViewGroup

android - 如何在构建 Android App Bundle 时指定环境变量