findViewById()可能会产生NullPointerException [英] findViewById() may produce NullPointerException

查看:235
本文介绍了findViewById()可能会产生NullPointerException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多这样的电话:

(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:


方法调用 getView()。findViewById(R.id .main_list_view)可能
产生 java.lang.NullPointerException less ...(Ctrl + F1)

Method invocation getView().findViewById(R.id.main_list_view) may produce java.lang.NullPointerException less... (Ctrl+F1)

此检查分析方法控制和数据流,以报告可能的
条件,这些条件始终为真或假,值为
的表达式被静态证明是常数,以及可能导致的情况
可违约合同违规。

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.

https://code.google.com/p/android/issues/detail?id=203345

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆