How to save a checkbox state in android app

前端 未结 3 363
醉话见心
醉话见心 2020-12-17 07:13

I have this app with a simple checkbox which adds a line to build.prop when the user presses it , the thing works but when i exit the app the check box is reseted , is there

相关标签:
3条回答
  • 2020-12-17 07:27

    Where did you get this extremely odd approach using getRuntime().exec()? Here's an easy working code sample for you using SharedPreferences. Replace your whole switch-statement with this one:

    switch(view.getId()) {
    case R.id.checkBox1:
        PreferenceManager.getDefaultSharedPreferences(this).edit()
            .putBoolean("checkBox1", checked).commit();
        break;
    }
    

    Inside onCreate() add this:

    CheckBox checkBox1 = (CheckBox) findViewById(R.id.checkBox1);
    boolean checked = PreferenceManager.getDefaultSharedPreferences(this)
        .getBoolean("checkBox1", false);
    checkBox1.setChecked(checked);
    

    Done.

    0 讨论(0)
  • 2020-12-17 07:37

    You can save the value in a preference and bind the value when it loads. for example,

    boolean checkedFlag = Preference.getBoolean("checkboxstate",false);
        CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
        cb.setChecked(checkedFlag);
    

    For setting values in preference

    SharedPreferences Preference = getSharedPreferences("pref", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = Preference.edit();
    editor.putBoolean("checkboxstate", checkboxstate);
    editor.commit();
    

    retrive value like

    SharedPreferences Preference = getSharedPreferences("pref", Activity.MODE_PRIVATE);
     boolean isCheckboxSet = Preference.getBoolean("checkboxstate");
    
    0 讨论(0)
  • 2020-12-17 07:49

    Yes, you can Just save the value of checkBox state in SharedPreferences and then retrieve them later when required

    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("state", "checked");
    editor.commit();
    

    later you can get it like

    SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
     String str = sp.getString("state");
    

    .See How to use SharedPreferences in Android to store, fetch and edit values


    You can use putBoolean() and getBoolean() methods of Sharedpreferences too as checkboxes have only two states

    0 讨论(0)
提交回复
热议问题