方法调用 'setTitle' 可能产生 'java.lang.NullpointerException'
Method invocation 'setTitle' may produce 'java.lang.NullpointerException'
我尝试使用以下代码为 ActionBar
设置标题:
@Override
public void onResume() {
((MainActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.artist));
super.onResume();
}
但 Android Studio 向我显示此警告:
我在 Whosebug 上搜索过,可以通过在我的代码前面添加此代码 if(getSupportActionBar()!=null)
来修复它。但这会导致我的脚本出错。
我不确定如何解决这个问题。
您有多种选择来执行您要求的操作:
1 - 忽略警告
不用多解释,这不是错误
2 - 优雅的解决方案
用 'if' 语句包裹你的行以确保它不为空
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle(getString(R.string.artist));
}
3 - 使用断言
assert getSupportActionBar() != null;
getSupportActionBar().setTitle(getString(R.string.artist));
4 - 移动警告
如果您在多个位置使用 'getSupportActionBar',您可以删除所有这些警告,而在 return 中,您只会收到有关 @NonNull 用法的警告。
@NonNull
@Override
public ActionBar getSupportActionBar() {
return super.getSupportActionBar();
}
我尝试使用以下代码为 ActionBar
设置标题:
@Override
public void onResume() {
((MainActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.artist));
super.onResume();
}
但 Android Studio 向我显示此警告:
我在 Whosebug 上搜索过,可以通过在我的代码前面添加此代码 if(getSupportActionBar()!=null)
来修复它。但这会导致我的脚本出错。
我不确定如何解决这个问题。
您有多种选择来执行您要求的操作:
1 - 忽略警告
不用多解释,这不是错误
2 - 优雅的解决方案
用 'if' 语句包裹你的行以确保它不为空
if(getSupportActionBar() != null) {
getSupportActionBar().setTitle(getString(R.string.artist));
}
3 - 使用断言
assert getSupportActionBar() != null;
getSupportActionBar().setTitle(getString(R.string.artist));
4 - 移动警告
如果您在多个位置使用 'getSupportActionBar',您可以删除所有这些警告,而在 return 中,您只会收到有关 @NonNull 用法的警告。
@NonNull
@Override
public ActionBar getSupportActionBar() {
return super.getSupportActionBar();
}