Reputation: 5
If I open the activity, the checkbox always stay checked and even if I unchecked it and leave the activity or closed the app it'll stay checked again after restarting the activity.
I've tried saving the state of the activity using the below code snippet.
checkBox1.setChecked(getSharedPreferences("NSUK", Context.MODE_PRIVATE).getBoolean("checkBox1", true));
checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getSharedPreferences("NSUK", Context.MODE_PRIVATE).edit().putBoolean("checkBox", isChecked).apply();
}
});
The checkbox is expected to always be in the state that the user leave it (checked or unchecked).
Upvotes: 0
Views: 155
Reputation: 887
The code is correct but you are storing and getting data form different values. You are storing in checkBox1 and reading from checkBox. Try with this
checkBox1.setChecked(getSharedPreferences("NSUK", Context.MODE_PRIVATE).getBoolean("checkBox", true));
checkBox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getSharedPreferences("NSUK", Context.MODE_PRIVATE).edit().putBoolean("checkBox", isChecked).apply();
}
});
Upvotes: 3