Search code examples
androidcheckboxsharedpreferencesoncheckedchanged

SharedPreferences getting deleted on app close


I have an app that uses SharedPreferences to keep track of the Users collection of items. But I've been getting complaints that they enter their items using a checkbox and when they restart the app their collection shows as empty.

Here is the code for the checkboxs

SharedPreferences data;

data = getSharedPreferences(filename, 0); 

checkbox = (CheckBox) findViewById(R.id.checkbox);

checkbox.setOnCheckedChangeListener(this);

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    // TODO Auto-generated method stub
    switch (buttonView.getId()) {
    case R.id.checkbox:
        bHave = checkbox.isChecked();
        if (bHave == true) {
            SharedPreferences.Editor e = data.edit();
            e.putBoolean(have, bHave);
            e.commit();
        } else {
            SharedPreferences.Editor e = data.edit();
            e.putBoolean(have, bHave);
            e.commit();
        }
        break;
    }
}

That writes to SharedPreferences as soon as the box is checked, so I know the data gets saved.

And here is the code to populate the checkbox

private void myGetChecked() {
    // TODO Auto-generated method stub

    bHave = data.getBoolean(have, false);

    if (bHave == true) {
        checkbox.setChecked(true);
    }
}

Which should get the data from the SharedPreferences.

A few points...

  1. It works on the 2 mobile devices i have to test on, a Droid X2 and an LG Spectrum 2.
  2. One's that mention it not working on, LG Optimus G, DROID RAZR HD, Desire HD and a Trac-Phone SGH-S959G.
  3. No errors are thrown, so I can't post a LogCat.
  4. I have double-checked and made sure all names match, in the keys and variables.
  5. I use the same preferences file for the whole app, but the way it's coded, only one activity reads/writes to the file at a time.

Anyone have any idea why some users are getting their data erased? And if you need any more info, let me know.


Solution

  • After I asked a few of the users whether they still had the issue, one replied that it was fixed. They did not say whether they had uninstalled the app before updating or whether they cleared the app data.

    Looks like this wasn't an issue at all, which was why I couldn't replicate it.