Proper way to handle Android Studio's NullPointerException lint warning

后端 未结 8 2027
终归单人心
终归单人心 2020-12-16 09:41

I\'m new to android/java programming and am confused how to properly deal with this warning.

Method invocation \'\' may produce \'Java.lang.NullPointe

8条回答
  •  情深已故
    2020-12-16 10:15

    As @matiash pointed out there is no one-size-fits-all solution.

    For me a good compromise was to disable NullPointerException warning for all calls to findViewById() and keep it for other method calls. That way I take responsibility for checking the resource ids but still get a benefit of getting warnings if I make other mistakes.

    To achieve this I added _ -> !null method contract with Android Studio quick fix menu.

    The action generated a following file file at android/support/v7/app/annotations.xml in my project root.

    
      
        
          
        
      
    
    

    Update: Unfortunately it doesn't survive Android Studio restarts :-( External annotations are really useful so I hope I'll figure out a way to make Android Studio load them after restart.

提交回复
热议问题