Is it recommended to check view for null with every findViewById call?

≯℡__Kan透↙ 提交于 2019-12-12 08:35:25

问题


When inflating an element with findViewById, Android Studio always warns me that my inflated view may return null

View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);

and suggests I do something like surround with my statement with a null check:

if (v != null) {
    mGridView = (GridView)v.findViewById(R.id.gridView);
}

Is it recommended to always do the mentioned null check before inflating an element?

EDIT: Adding lint pictures


回答1:


You can ignore this warning and move ahead with your code if you are sure that the id you are passing does exist within your applications context, if you are not sure then its better to do a null check before accessing the elements in this view because

     View v = inflater.inflate(R.layout.fragment_photo_gallery, container, false);

will return null in case "R.layout.fragment_photo_gallery" is incorrect or invalid renderring v as null .

Thus an attempt like this

     mGridView = (GridView)v.findViewById(R.id.gridView);

may result in a null pointer exception




回答2:


I think you should never do that.

If you do that you are masking a logic error in your program, in case you are passing a wrong id to your findView.

If you are passing a correct id but for any reason inflater returns null that's Android problem (that will never actually happen) and you also should do nothing.

I think this warning does not come from Android Lint.



来源:https://stackoverflow.com/questions/23569225/is-it-recommended-to-check-view-for-null-with-every-findviewbyid-call

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