正确的方法来处理Android Studio的NullPointerException lint警告 [英] Proper way to handle Android Studio's NullPointerException lint warning

查看:959
本文介绍了正确的方法来处理Android Studio的NullPointerException lint警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android / java编程的新手,我很困惑如何正确处理这个警告。

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


方法调用''可能生成'Java.lang.NullPointerException'

Method invocation '' may produce 'Java.lang.NullPointerException'

我应该使用断言取消警告吗?

Should I be ussing assert to remove the warning?

或而是一个运行时异常?

Or rather a runtime exception?

任何帮助将不胜感激。

推荐答案

我怀疑这个问题可以得到最终的回答,因为这是一个意见问题。或者至少我相信 - 也是一种观点。 :)

I doubt this question can be answered conclusively, as it's a matter of opinion. Or at least I believe so -- an opinion too. :)

我知道你想要0警告(一个非常值得称道的目标),但可能没有一刀切的问题。那说...

I understand you want "0 warnings" (a very laudable goal) but there's probably not a "one size fits all" issue. That said...

我相信你应该做的事情:

Things I believe you should not do:


  • 使用断言。虽然您可以添加断言语句,但Dalvik会忽略它们。您可以根据需要配置仿真器以使用它们,但不能使用真实设备(请参阅我可以在Android设备上使用assert吗?)。因此虽然它可能会删除警告,但实际上它没用。

  • 让方法抛出 NullPointerException 。一般来说,这是一个坏主意。在这种情况下,由于你可能覆盖 onOptionsItemSelected(),它甚至不可能。

  • Use assert. While you can add an assert statement, Dalvik ignores them. You can configure an emulator to use them if you want, but not a real device (see Can I use assert on Android devices?). So while it would possibly remove the warning, it's useless in practice.
  • Have the method throw NullPointerException. This would be a bad idea, generally. In this case, since you're probably overriding onOptionsItemSelected(), it's not even possible.

检查(变量!= null)通常是最好的方法。但是,该怎么办,还有一些其他的选择。

Checking for (variable != null) is generally the best approach. What to do if it is, though, presents some other options.


  • 如果这是一个问题,你可以恢复来自,即使 searchView 不存在,你也可以继续申请,就这样做。例如,只需从方法返回。但是,记录这种情况是个好主意,所以你可以在测试时发现它。

  • 否则,如果无法继续,则抛出异常。您想要提前失败,以便问题很容易被发现。这种情况的一个合理的例外是IllegalStateException(请参阅 Java等效于.NET System.InvalidOperationException )。它基本上表明此方法是在不适当的时间执行的。但请注意,作为 RuntimeException ,这些异常未经检查,因此可能会导致应用程序崩溃。

  • If it's a problem you can recover from, i.e. you can continue the application even though the searchView isn't there, just do so. For example, just return from the method. It's a good idea to log this situation though, so you can spot it while testing.
  • Otherwise, if continuing isn't possible, throw an exception. You want to fail early, so that the problem can be easily detected. A reasonable exception for this case would be IllegalStateException (see Java equivalent to .NET System.InvalidOperationException). It basically indicates that this method was executed at an inappropriate time. Be careful though, that as a RuntimeException, these exceptions are unchecked, and hence will probably cause the app to crash.

这篇关于正确的方法来处理Android Studio的NullPointerException lint警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆