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

查看:41
本文介绍了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 更少... (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 的返回值被视为可空(或分别为非空)并在分析期间用于检查无效性合同,例如报告可能的 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

@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 -> fail") — 一个典型的 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?

推荐答案

这是 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/问题/详细信息?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天全站免登陆