问题描述
我有很多这样的电话:
(ListView) getView().findViewById(R.id.main_list_view);
(TextView) getView().findViewById(R.id.items_no);
....
并且AndroidStudio告诉我他们可能会产生 NullPointerException
:
and AndroidStudio tells me that they may procude a NullPointerException
:
此检查分析方法控制和数据流,以报告可能的
条件,这些条件始终为真或假,值为
的表达式被静态证明是常数,以及可能导致的情况
可违约合同违规。
This inspection analyzes method control and data flow to report possible conditions that are always true or false, expressions whose value is statically proven to be constant, and situations that can lead to nullability contract violations.
变量,方法参数和
返回值标记为 @Nullable
或 @NotNull
被视为可空的
(或分别为非null),并在分析期间用于检查
可空性合约,例如报告可能 NullPointerException
错误。
Variables, method parameters and return values marked as @Nullable
or @NotNull
are treated as nullable (or not-null, respectively) and used during the analysis to check nullability contracts, e.g. report possible NullPointerException
errors.
可以使用定义更复杂的合同@Contract
注释,例如:
More complex contracts can be defined using @Contract
annotation, for example:
@Contract(_,null - > null )
- 如果第二个参数为null,则方法返回null
@Contract(_,null - > null; _,!null - >!null )
- 如果第二个参数为null且null为null,则返回null,否则
@Contract("_, null -> null")
— method returns null if its second argument is null @Contract("_, null -> null; _, !null -> !null")
— method returns null if its second argument is null and not-null otherwise
@Contract(true - >失败)
- 一个典型的 assertFalse
方法,如果将true传递给它,则抛出异常
@Contract("true -> fail")
— a typical assertFalse
method which throws an exception if true is passed to it
可以将检查配置为使用自定义 @Nullable
@NotNull
注释(默认情况下,将使用annotations.jar中的那些)
The inspection can be configured to use custom @Nullable
@NotNull
annotations (by default the ones from annotations.jar will be used)
幸运的是,有作为,但这个代码是否有改进我可以做?
Luckily everithing works, but is there an improvement to this code I can made?
推荐答案
这是一个已知的问题e在android.support.v7.app.AppCompatActivity中已在v24中修复。
This is a known issue in android.support.v7.app.AppCompatActivity and it has been fixed in v24.
android.support.v4.app.FragmentActivity或android.app.Activity
You won't have any issues with android.support.v4.app.FragmentActivity or android.app.Activity
这篇关于findViewById()可能会产生NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!