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

若如初见. 提交于 2019-11-30 06:39:41

问题


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;
}

回答1:


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);
}



回答2:


i believe the google notepad3 tutorial explains about saving and restore state http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html

save the state bundle in onSaveInstanceState() then get the bundle back in onStart()

Hope that helps

Edit: also check this one, its more concise. onSaveInstanceState () and onRestoreInstanceState ()



来源:https://stackoverflow.com/questions/5692869/how-to-save-the-state-of-an-android-checkbox-when-the-users-exits-the-applicatio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!