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...
- It works on the 2 mobile devices i have to test on, a Droid X2 and an LG Spectrum 2.
- One's that mention it not working on, LG Optimus G, DROID RAZR HD, Desire HD and a Trac-Phone SGH-S959G.
- No errors are thrown, so I can't post a LogCat.
- I have double-checked and made sure all names match, in the keys and variables.
- 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.