Daniele Daniele - 1 year ago 79
Java Question

How do I store if a CheckBox has been checked?

I have an Activity that doesn't have to be displayed anymore if a "Don't show anymore" CheckBox is checked but I can't figure out how to make it work.

This is what I have tried up until now:

public class PopUpInfoActivity extends Activity {
static final String PREFS = "preference_file";

public void onCreate(Bundle state){

CheckBox chk = (CheckBox) findViewById(R.id.dontshow_checkbox);
chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));

chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//store isChecked to Preferences
SharedPreferences settings = getSharedPreferences(PREFS,0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", false);

PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).apply();

This code still doesn't work because if I check the CheckBox and kill and restart the app, the activity still appears how can I make it work?

I would really appreciate any help!

Answer Source

Use this for setting checkBox value

chk.setChecked(PreferenceManager.getDefaultSharedPreferences(this).getBoolean("value", false));

use this for getting checkBox value.

chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

       public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
          //store isChecked value in shareprefernce

          PreferenceManager.getDefaultSharedPreferences(PopUpInfoActivity.this).edit().putBoolean("value", isChecked).commit();

enjoy coding..........