findViewById() 可能会产生 NullPointerException

findViewById() may produce NullPointerException

我有很多这样的电话:

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

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

这是因为 getView() 可能 return 为 null 并被注释为 @Nullable,请查看来源及其 JavaDoc - CTRL+单击代码中的 getView() 调用。

/**
 * Get the root view for the fragment's layout (the one returned by {@link #onCreateView}),
 * if provided.
 * 
 * @return The fragment's root view, or null if it has no layout.
 */
@Nullable
public View getView() {
    return mView;
}

您可以自己包装代码并检查 null 以使警告消失,或者将光标放在 findViewById() 调用中的任意位置,等待几秒钟让灯泡出现(或按 Alt+Enter ) 然后选择建议的解决方案之一。

这是 android.support.v7.app.AppCompatActivity 中的已知问题,已在 v24.

中修复

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

android.support.v4.app.FragmentActivity 或 android.app.Activity

不会有任何问题

应该忽略这个问题;

正如@DanDar3 所写 -> getView() 可以 return null 并且 AndroidStudio 强调了这一点。

但如果您真的想让 AndroidStudio 快乐 - 当然可以...:[=​​18=] 只是断言视图不为空:

View view = getView();
assert view != null;
(ListView) view.findViewById(R.id.main_list_view);
(TextView) view.findViewById(R.id.items_no);