1

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));
Tim
  • 41,901
  • 18
  • 127
  • 145
John K
  • 371
  • 5
  • 26

2 Answers2

6

You are accessing a completely different shared preference instance.

"com.example.xyle"

and

"com.example.xyz"

Please change them to be equal

IAmGroot
  • 13,760
  • 18
  • 84
  • 154
  • Great, i didn't noticed that mistake that was the issue, ill accept the your answer in 9 minutes. – John K Aug 01 '17 at 08:41
  • 1
    @I.Mytyuk No problem. You could consider using Default Shared Preferences. Rather than private, unless there is a specific reason for it. Also, `apply()` is better than `commit()` https://stackoverflow.com/a/12074219/940834 – IAmGroot Aug 01 '17 at 08:44
  • 2
    @I.Mytyuk, to avoid such a situation try not to use inline strings, but use constants. – Vladyslav Matviienko Aug 01 '17 at 08:45
  • 1
    @VladMatvienko Yep a good suggestion for the private preference route. Minimize typos where possible for resused strings. – IAmGroot Aug 01 '17 at 08:46
  • 1
    @VladMatvienko sure i will, i'm just new in android so i still have much to learn. – John K Aug 01 '17 at 08:47
1

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();
        }
Pratik Popat
  • 2,891
  • 20
  • 31