getSupportActionBar()NullPointerException [英] getSupportActionBar() NullPointerException
问题描述
在onCreate()
活动方法中,我有ToolBar
的这段代码:
In onCreate()
method of activity I have this code for ToolBar
:
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
我的IDE使我感到getSupportActionBar().setDisplayHomeAsUpEnabled(true);
可能产生 NullPointerException
.
My IDE warms me that getSupportActionBar().setDisplayHomeAsUpEnabled(true);
may produce NullPointerException
.
我的问题是我应该忽略它,如何解决它吗?
My question is should I ignore it and how can I fix it anyway?
推荐答案
IDE会警告您潜在的NullPointerException
,因为在许多情况下,应用可能会抛出一个.例如,您可能为整个Application
(或仅针对相关的activity
)使用了 NoActionBar 主题,但是您仍然尝试使用getActionBar()
(或getSupportActionBar()
).
The IDE warns you about a potential NullPointerException
because there are many cases where the app could throw one. For the example you could be using a NoActionBar theme for your whole Application
(or just for the concerned activity
), but still you're trying to retrieve a reference to the action bar using getActionBar()
(or getSupportActionBar()
).
只需忽略警告,但请记住上面的提示.
Just ignore the warning, but keep in mind the notes above.
更新:
您可以通过显式检查可空性来摆脱此警告:
You can get rid of the warning by explicitly checking for nullability:
toolbar = (Toolbar) findViewById(R.id.tool_bar);
if (toolbar != null) {
// you can safely invoke methods on the Toolbar
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
} else {
// Toolbar is null, handle it
}
这篇关于getSupportActionBar()NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!