Moussa Harajli
Moussa Harajli

Reputation: 1516

Android Shared Preferences Not Comitting

I have a switch i am toggling in the app. When i close the app i want the last toggle state to save. When the app opens it will set the toggle state to the last saved state. I am using SharedPreferences to do this. For some reason my preferences are not saving. I have looked over my code and could not find any problems.

// Set some preferences
    Preferences = getApplicationContext().getSharedPreferences(getPackageName(), 0);

    // Set the monitor toggle to on or off
    final SwitchCompat monitorToggle = (SwitchCompat)findViewById(R.id.monitorToggleButton);
    boolean monitorStatus = Preferences.getBoolean("monitorStatus", true);
    monitorToggle.setChecked(monitorStatus);

    // Setup the monitor toggle view
    LinearLayout monitorToggleView = (LinearLayout)findViewById(R.id.monitorToggle);
    monitorToggleView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            monitorToggle.toggle();
            Preferences.edit().putBoolean("monitorStatus", monitorToggle.isChecked());
            Preferences.edit().commit();
        }
    });

The "Preferences" variable is a private variable in the class

private SharedPreferences Preferences;

Upvotes: 1

Views: 70

Answers (3)

ci_
ci_

Reputation: 8774

The other answers are correct but omit to explain that the mistake was to call edit() twice, i.e. you have created a second Editor, made no changes, and commited. You never committed the changes to the first Editor.

Instead of this:

Preferences.edit().putBoolean("monitorStatus", monitorToggle.isChecked());
Preferences.edit().commit();

you could just do:

Preferences.edit().putBoolean("monitorStatus", monitorToggle.isChecked()).commit();

There's no need to store the Editor in a variable.

Upvotes: 2

jb15613
jb15613

Reputation: 359

Try using

SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(YourActivity.this);
SharedPreferences.Editor editor = prefs.edit();

editor.putBoolean("monitorStatus", monitorToggle.isChecked());
editor.commit();

Upvotes: 2

MorZa
MorZa

Reputation: 2325

Try this:

Editor editor = Preferences.edit();
editor.putBoolean("monitorStatus", false);
editor.commit();

Upvotes: 1

Related Questions