Switch item always return null

Viewed 125

I have switch item inside the navigation drawer(activity_main_drawer.xml) and I got a reference to it in the mainactivity.java as following

Switch s = findViewById(R.id.switch);

before I perform any task using it I check if it is null

if(s != null){....}

android studio gives me a warning saying "condition is always true",However, when I run it I get nullpointerexception, Here is my code

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();
                }
            }
        });}
}
1 Answers

The if condition will always be true because you will always run s.setchecked method before reaching that if statement, so if s object is already null an exception will be thrown and the condition checking if the object is null will never be reached.

Related