Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

enter image description hereenter image description here

like image 506
Adam Johns Avatar asked May 09 '14 16:05

Adam Johns


1 Answers

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.

like image 142
Alexander Kulyakhtin Avatar answered Nov 15 '22 18:11

Alexander Kulyakhtin