How to save the state of an Android CheckBox when the users exits the application?

Varundroid picture Varundroid · Apr 17, 2011 · Viewed 18.4k times · Source

Is there any way by which I can save the state of my checkboxes (checked or unchecked) when user exits the application so that I can reload this state when the application restarts?

@Override
public void onPause()
{

    super.onPause();
    save(itemChecked);
}
@Override
public void onResume()
{
    super.onResume();
    checkOld = load();

    for (int i = 0 ; i < checkOld.length; i++)
    {
        notes.ctv.get(i).setChecked(checkOld[i]);
    }
}
@Override
public void onRestart()
{
    super.onResume();
    checkOld = load();

    for (int i = 0 ; i < checkOld.length; i++)
    {
        notes.ctv.get(i).setChecked(checkOld[i]);
    }
}

private void save(final boolean[] isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
 insertState();
 for(Integer i = 0; i < isChecked.length; i++)
 {
     editor.putBoolean(i.toString(), isChecked[i]);
 }
editor.commit();
}

private boolean[] load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    boolean [] reChecked = new boolean[itemChecked.length];
    for(Integer i = 0; i < itemChecked.length; i++)
    {
         reChecked[i] = sharedPreferences.getBoolean(i.toString(), false);
    }
    return reChecked;
}

Answer

Wroclai picture Wroclai · Apr 17, 2011

Combine onPause() and onResume() to save and load your CheckBox value.

Sample code:

@Override
public void onPause() {
    super.onPause();
    save(mCheckBox.isChecked());
}

@Override
public void onResume() {
    super.onResume();
    mCheckBox.setChecked(load());
}

private void save(final boolean isChecked) {
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean("check", isChecked);
    editor.commit();
}

private boolean load() { 
    SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
    return sharedPreferences.getBoolean("check", false);
}