问题描述
即使我已经使用getSupportActionBar()
设置了支持操作栏,我是否应该对getSupportActionBar()
方法进行空检查?
Should I null check the getSupportActionBar()
method even if earlier in that method I have set the support action bar using getSupportActionBar()
?
在onCreate()
中,我有三行
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle(getIntent().getStringExtra(TITLE_KEY));
然后,Android Studio给我警告
Android Studio then gives me the warning
"Method invocation may produce java.lang.NullPointerException"
假设 findViewById 方法确实返回了有效的ToolBar
对象,我是否仍需要对getSupportActionBar()
方法进行空检查,还是忽略警告是否安全?
Assuming that the findViewById method does return a valid ToolBar
object, do I still need to null check the getSupportActionBar()
method or is it safe to just ignore the warning?
推荐答案
我的建议是:-不检查null,因为警告不是错误
您正在谈论的警告说可能会产生",而不是说会产生".
My suggestion is :- Not to check for null because Warnings are not Errors
warning which you are talking about says "it may produce".It don't say 'will must produce'.
但是,如果要再次确认,可以检查是否为空
But if you want to double sure you can check for null
这篇关于在setSupportActionBar之后,getSupportActionBar可以为null吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!