Why does the swtich return to the initial phase?

I’ve created a swich and i’m saving the boolean value in to the sharedPreferences, but when i restore the activity the switch return to OFF while i want to keep it ON if it was turned ON while if it was turned OFF to keep it OFF.

Here’s my switch code:

        buttonSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
            if(isChecked){
                switched = "ON";
                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                editor.putBoolean("SWTCH", buttonSwitch.isChecked());
                editor.commit();
            }else{
                switched = "OFF";
                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                editor.putBoolean("SWTCH", buttonSwitch.isChecked());
                editor.commit();
            }
        }
    });

And here is onCreate SharedPreferences:

    SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyle", MODE_PRIVATE);
    buttonSwitch.setChecked(sharedPrefs.getBoolean("SWTCH", false));

You are accessing a completely different shared preference instance.

"com.example.xyle"

and

"com.example.xyz"

Please change them to be equal

Use same preference name for both reading and writing.

You can also enhance onCheckedChanged to:

        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                switched = isChecked ? "ON":"OFF";
                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                editor.putBoolean("SWTCH", isChecked);
                editor.commit();
        }