【问题标题】:How to tell Android Studio that the null check has been done?如何告诉 Android Studio 已完成空值检查?
【发布时间】:2016-10-03 12:15:39
【问题描述】:

如何在 Android Studio 中配置 Assert/Check 方法?

我使用 Mosby MVP 框架,在 Presenter 中我经常使用这种模式:

if (isViewAttached()) {
    getView().someViewMethod();
}

getView() 标记为 @Nullable,因此 Android Studio 向我显示警告 method invocation 'someViewMethod' could produce NullPointerException。它不明白我以前检查过它。

我找到了关于配置断言/检查方法的绝妙答案:https://stackoverflow.com/a/19319326/1263771

但是在新的Android Studio中不能这样做,因为它有不同的设置界面。那么,在上一个 Studio 中怎么做呢?

【问题讨论】:

  • 你试过@SuppressWarnings("ConstantConditions") 吗?
  • if(getView()!=null) 适合我。
  • 不明白我以前检查过它。 ...好吧不...final View view = getView(); if(view != null && isViewAttached()) view.someViewMethod();
  • @PierGiorgioMisley 是的,这是真的,我只有 isViewAttached(),而且我知道如果 isViewAttached() 为真,那么 getView() 总是返回不为 null。我搜索为 lint 配置此规则的方法。查看问题中的链接,它包含操作方法,但不适用于上一个 Android Studio。

标签: android android-studio mosby


【解决方案1】:

目前最简单的方法是使用

V view = getView();
if (view != null){ // instead of isViewAttached()
   ...
}

@Nullable 注释很可能会在 Mosby 3.0 的下一个主要版本中被删除

【讨论】:

    【解决方案2】:

    完全同意你@tse。这是一个绝妙的答案,但已经过时了。

    但我找到了一个有用的解决方案。您必须将 isViewAttached() 方法设为 static 并将视图作为参数发送。

    protected static boolean isViewAttached(final View view) {
        return view != null && view.isAttached();
    }
    
    if (isViewAttached(getView())) {
       getView().someViewMethod();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-09
      相关资源
      最近更新 更多