Proper way to handle Android Studio's NullPointerException lint warning

后端 未结 8 1922
终归单人心
终归单人心 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:04

    I've used Objects.requireNonNull() which is a good way IMO. As @matiash mentioned, this is not a fool-proof way for every use case, but where you are sure that data won't be null, you can use this approach to get rid of the warning. And if it does fail for some unknown reason, you will get NullPointerException which you will get anyway without using this.

    // before
    cal.setTime(date);
    
    // after
    cal.setTime(Objects.requireNonNull(date));
    

提交回复
热议问题