findViewById() may produce NullPointerException

瘦欲@ 提交于 2019-12-19 06:53:44

问题


I have many of these calls:

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

and AndroidStudio tells me that they may procude a 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)

Luckily everithing works, but is there an improvement to this code I can made?


回答1:


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

You won't have any issues with android.support.v4.app.FragmentActivity or android.app.Activity




回答2:


You should ignore the problem;

As @DanDar3 wrote -> getView() can return null and AndroidStudio highlights that.

But if you really want to make AndroidStudio happy - sure you can...:
Just assert view is not null:

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



回答3:


That is cause getView() may return null and is annotated as @Nullable, check out the sources and its JavaDoc - CTRL+Click on getView() call in your code.

/**
 * 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;
}

You can wrap your code yourself and check for null to have the warning go away, or otherwise place the cursor anywhere inside findViewById() call, wait couple of seconds for the lightbulb to show up (or press Alt+Enter) and then choose one of the suggested solutions.



来源:https://stackoverflow.com/questions/33671216/findviewbyid-may-produce-nullpointerexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!