首页 > 解决方案 > 切换项总是返回 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();
                }
            }
        });}
}

标签: androidandroid-studio

解决方案


if 条件将始终为真,因为您将始终s.setchecked在到达该 if 语句之前运行方法,因此如果 s 对象已经为 null,则会引发异常,并且永远不会达到检查对象是否为 null 的条件。


推荐阅读