gpt4 book ai didi

java - findViewById() 可能会产生 NullPointerException

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:25 24 4
gpt4 key购买 nike

我有很多这样的电话:

(ListView) getView().findViewById(R.id.main_list_view);
(TextView) getView().findViewById(R.id.items_no);
....

AndroidStudio 告诉我他们可能会产生一个NullPointerException:

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.

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.

More complex contracts can be defined using @Contract annotation, for example:

@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") — a typical assertFalse method which throws an exception if true is passed to it

The inspection can be configured to use custom @Nullable @NotNull annotations (by default the ones from annotations.jar will be used)

幸运的是一切正常,但是我可以对这段代码进行改进吗?

最佳答案

这是 android.support.v7.app.AppCompatActivity 中的一个已知问题,已在 v24 中修复。

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

android.support.v4.app.FragmentActivity 或 android.app.Activity 不会有任何问题

关于java - findViewById() 可能会产生 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com