android - 切换项总是返回 null
问题描述
我在导航抽屉(activity_main_drawer.xml)中有开关项目,我在 mainactivity.java 中得到了对它的引用,如下所示
Switch s = findViewById(R.id.switch);
在我使用它执行任何任务之前,我检查它是否为空
if(s != null){....}
android studio 给我一个警告说“条件始终为真”,但是,当我运行它时,我得到 nullpointerexception,这是我的代码
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_gallery, R.id.nav_slideshow, R.id.nav_draw, R.id.dark_mode)
.setDrawerLayout(drawer)
.build();
SharedPreferences sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
mEditor = sharedPreferences.edit();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
Switch s = findViewById(R.id.dark_mode);
if(sharedPreferences.getInt("DARK_MODE", 0) == 1){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
s.setChecked(true);
}
else {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
s.setChecked(false);
}
if (s != null){
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
mEditor.putInt("DARK_MODE", 1);
mEditor.apply();
}
else{
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
mEditor.putInt("DARK_MODE", 0);
mEditor.apply();
}
}
});}
}
解决方案
if 条件将始终为真,因为您将始终s.setchecked
在到达该 if 语句之前运行方法,因此如果 s 对象已经为 null,则会引发异常,并且永远不会达到检查对象是否为 null 的条件。
推荐阅读
- reactjs - Ant Design Form 组件不显示输入值
- typescript - 参数类型 URL 不可分配给参数类型字符串
- react-native - 世博会反应原生苹果登录在TestFlight中崩溃
- c# - C# 创建实例级接口的最佳方法
- javascript - Angular 在单击 ng-select 后无法单击表
- c# - C# 多个相同的表单,来自 SQL 数据库的不同值
- python - 如何根据多个条件替换 NaN 值?
- mysql - Transact-SQL 可以像 MySQL 一样自动检测功能依赖关系吗?
- python - 无法在 Django 的网页上显示模板变量
- python - Django 没有配置 WSGI 守护进程