How to save a checkbox state in android app

15,293

Solution 1

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.

Solution 2

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

Solution 3

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

Share:
15,293
HashAL78
Author by

HashAL78

Looking for that future.

Updated on June 04, 2022

Comments

  • HashAL78
    HashAL78 almost 2 years

    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 a way to prevent this with adding a sample code in your post because i am still newbie to android apps.

    MainActivity.java

    package com.mythi.tests;
    
    import java.io.DataOutputStream;
    import java.io.IOException;
    
    import android.app.Activity;
    import android.content.SharedPreferences;
    import android.os.Bundle;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.widget.CheckBox;
    import android.widget.CompoundButton;
    import android.widget.CompoundButton.OnCheckedChangeListener;
    
    public class MainActivity extends Activity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }
    
        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
    
        public void onCheckboxClicked(View view) {
            // Is the view now checked?
            boolean checked = ((CheckBox) view).isChecked();
    
            // Check which checkbox was clicked
            switch(view.getId()) {
                case R.id.checkBox1:
                    if (checked){
                        try{
                            Process su = Runtime.getRuntime().exec("su");
                            DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
                            outputStream.writeBytes("cp /system/build.prop /system/build.prop.bak\n");
                            outputStream.writeBytes("echo 'persist.sys.scrollingcache=3' >> /system/build.prop\n");
                            outputStream.flush();
    
                            outputStream.writeBytes("exit\n");
                            outputStream.flush();
                            su.waitFor();
                        }catch(IOException e){
    
                        }catch(InterruptedException e){
    
                        }
            }else{
                try{
                    Process su = Runtime.getRuntime().exec("su");
                    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());
    
                    outputStream.writeBytes("rm -r /system/build.prop\n");
                    outputStream.writeBytes("mv /system/build.prop.bak /system/build.prop\n");
                    outputStream.flush();
    
                    outputStream.writeBytes("exit\n");
                    outputStream.flush();
                    su.waitFor();
                }catch(IOException e){
    
                }catch(InterruptedException e){
    
                }   
                break;
            } 
    
           }
    
       }
    
    }
    

    activity_main.xml

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:paddingBottom="@dimen/activity_vertical_margin"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:paddingTop="@dimen/activity_vertical_margin"
        tools:context="com.mythi.tests.MainActivity" >
    
        <CheckBox
            android:id="@+id/checkBox1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="169dp"
            android:onClick="onCheckboxClicked"
            android:text="CheckBox" />
    
    </RelativeLayout>
    
  • HashAL78
    HashAL78 almost 10 years
    where shall i add the codes ... sorry for being so nooby
  • 0101100101
    0101100101 almost 10 years
    @user3932803 My answer shows you that in two steps. Copy-pasting should work. If not, drop a comment there.
  • Jithu
    Jithu almost 10 years
    @user3932803 :SharedPreferences used to store valus, which saves in a file, acts like a permanant storage. you can use this as you need. You can use a global variable to keep the changed checkbox value and store it when activity closes, like onDestroy() and retrieve it in onCreate(). Bind the value to checkbox where you showing it, may be in onCreate after binding the preference value.
  • Jithu
    Jithu almost 10 years
    if you Still has the doubt, send me your mail id, I will send you a sample project.