vendredi 13 novembre 2015

Can't use SharedPreferences with some checkboxes

I have a fragment that starts an activity in which I have various checkboxed (Checkbox1, checkbox2 and so on). I need to keep the status ticked/unticked saved even after I return to the fragment and I start again the activity.

I tried this code but it's not working

        final CheckBox checkBox5 = (CheckBox) findViewById(R.id.checkBox2);
    checkBox5.setChecked(false);

    checkBox5.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (checkBox5.isChecked()) {
                buttonSound.start();
            } else {
                buttonSound.start();
            }
            SharedPreferences pref5 = PreferenceManager.getDefaultSharedPreferences(.this);                SharedPreferences.Editor editor5 = pref5.edit();
            editor5.putBoolean("checkbox", checkBox5.isChecked());
            editor5.commit();
            if (pref5.getBoolean("checkbox", false) == true){
                checkBox5.setChecked(true);
            } else{
                checkBox5.setChecked(false);
            }
        }
    });

Can anyone enlighten me on what I am doing wrong?

The activity is declared in manifest and I simply want to get back from this Activity to a Fragment and while going from the Fragment to this Activity finding these checkboxes flagged!




Aucun commentaire:

Enregistrer un commentaire