0

I'm confused about what's happening in the following code. It's actually doing what I want but I thought I'd have to do more work. In the onCreate method the checkboxes are retaining their checked or unchecked state from a previous run even after I force quit the app. It's saving their state even though the Log message "onCreate found" is never printed and the "adding account" message is printed and the cbp2.setChecked(false) seems to be ignored.

What's going on?


public class SettingsActivity extends PreferenceActivity {
private final static String LOGTAG = "SettingsActivity";

@Override
@SuppressWarnings("deprecation")
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Load preference data from XML
    this.addPreferencesFromResource(R.xml.preferences_settings);

    Set<String> accounts = new HashSet<String>();

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
        accounts = Accounts.getAccounts(this);
    }

    final PreferenceCategory cat = (PreferenceCategory) this
            .findPreference("key_accounts");

    for (String account : accounts) {
        final CheckBoxPreference cbp = (CheckBoxPreference) this
                .findPreference("key_" + account);

        if (cbp != null) {
            Log.d(SettingsActivity.LOGTAG, "onCreate found: " + account
                    + (cbp.isChecked() ? ", checked" : ""));

            continue;
        }

        Log.d(SettingsActivity.LOGTAG, "adding account " + account);

        final CheckBoxPreference cbp2 = new CheckBoxPreference(this);

        // make sure each key is unique
        cbp2.setKey("key_" + account);
        cbp2.setTitle(account);
        cbp2.setChecked(false);

        cat.addPreference(cbp2);
    }
}

}


Here's the top of my preferences xml:

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
    android:key = "key_accounts"
    android:title = "@string/title_accounts">
</PreferenceCategory>
lumpynose
  • 967
  • 4
  • 12

1 Answers1

0

It really depends how you defined the preference XML. Usually it saves the setting in SharedPreferences and therefore every change is promptly written back to SharedPrefs and therefore persistent.

RaB
  • 1,545
  • 13
  • 16