9

until now I couldn't find any answer that suits my problem/question. In android studio it often shows a notice that e.g. findViewById may produce a NPE, althogh i know the item IS existing in the layout I use. I also never got a NPE thrown at this locations at runtime, so why the warning/notice?

I just don't know how I have to react/handle to such warnings/infos in the code view? Are there any tips to avoid that messages (because for me it looks like valid and working code)? It's only the warnings in the code view, that makes me uncertain.

Here a snippet where a warning is shown on findViewByID.

//fetch predefined item layout
row = inflater.inflate(R.layout.view_searchresult_item,null);
//get table layout for inserting items
TableLayout itemtablelayout = (TableLayout)row.findViewById(R.id.resultitem_tablelayout);
Faenor
  • 633
  • 8
  • 23
  • Warnings are not an Error. And the warning which you are talking about says "it may produce", don't say 'it must produce'. So choice is yours. Either add null check or not – Pankaj Kumar Sep 03 '13 at 09:22
  • 1
    That's what my question is aiming for. How is that usually done? Nullchecks for every warning? In this case I'm quite sure that never happens anthing, because the id/item is always present. Of course, for variable cases a nullcheck is used by me. – Faenor Sep 03 '13 at 09:31
  • I said "So choice is yours.". If you are sure that `findViewById` in your code will never be cause of NPE, then don't add the null check. – Pankaj Kumar Sep 03 '13 at 09:35
  • Could you maybe write this in an answer, so I can mark this as solved please? – Faenor Sep 03 '13 at 09:46
  • Possible duplicate of [Is it recommended to check view for null with every findViewById call?](http://stackoverflow.com/questions/23569225/is-it-recommended-to-check-view-for-null-with-every-findviewbyid-call) – August Janse May 13 '16 at 09:19

1 Answers1

3

Warning is not an Error. And the warning which you are talking about says "it may produce", don't say 'it must produce'. So choice is yours. Either add null check or not


So, If you are sure that findViewById in your code will never be cause of NPE, then don't add the null check.

Pankaj Kumar
  • 81,967
  • 29
  • 167
  • 186