1

i have a checkbox in my app and i want to know if its possible to for the app to remember the last state of the checkbox i mean when the checkbox is checked and the app is closed when the app is opened again the checkbox is still checked same with unchecked.

this is how i did it.

i have this code on OnResume

@Override
     protected void onResume() {
      super.onResume();
     if(checkbox.equals(true)){
                  checkbox.setChecked(true);

              }else{
                  checkbox.setChecked(false); 
              }

     }

and this is my onchecklistener

checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                    boolean isChecked) {
                // TODO Auto-generated method stub
                if(checkbox.isChecked()){
                      checkbox.setChecked(true);
                      publicvar.displayMessage(Login.this, "check", 0);

                  }else{
                      checkbox.setChecked(false); 
                      publicvar.displayMessage(Login.this, "uncheck", 0);
                  }
            }

        });

unfortunately it didn't work

Giant
  • 1,619
  • 7
  • 33
  • 67

5 Answers5

3

I agree with Ted Hopp.

try this :

public void saveCheckBoxState(boolean isChecked){
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = prefs.edit();

    editor.putBoolean("key",isChecked);
    editor.commit();
}

Call saveCheckBoxState(boolean) in your onCheckedChanged()

and

public boolean getCheckBoxState(){
  SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
  return prefs.getBoolean("key", false);
}

call getCheckBoxState() in onResume() of your activity.

Ritesh Gune
  • 16,629
  • 6
  • 44
  • 72
  • If OP is targeting API level 9 or later, it would be better (in this code) to use `editor.apply()` instead. – Ted Hopp Apr 08 '14 at 03:48
  • @TedHopp what is different between `commit` and `apply`? why it would be better? – Shayan Pourvatan Apr 08 '14 at 03:51
  • @TedHopp what do you mean by editor.apply() im targeting API 19 the highest – Giant Apr 08 '14 at 03:51
  • @HakHak for Ted suggest minimum API that your application to suppert is matter not targeting API – Shayan Pourvatan Apr 08 '14 at 03:53
  • @shayanpourvatan my lowest api is API 8 so does that mean i cant use shared preference sorry wasnt able to read the documentation for now i wanted to test the code – Giant Apr 08 '14 at 03:55
  • 1
    @HakHak - `apply()` was introduced in API 9. It actually does the writing to persistent storage in a separate thread, thus letting the UI thread remain a bit more responsive. You can use `SharedPreferences` just fine in API 8; just use `commit()` instead of `apply()`. – Ted Hopp Apr 08 '14 at 03:56
  • you can use @HakHak, use this answer or see http://stackoverflow.com/questions/7496840/get-android-shared-preferences-value-in-activity-normal-class, but you can't use Ted suggest – Shayan Pourvatan Apr 08 '14 at 03:56
  • 1
    @HakHak you can use Sharedpreference no matter what your lowest API is. However the apply() was introduced in API 9, whereas commit() was there since API 1. So if you intend to use both ,then you will have to check for API version in the code and then select commit or apply accordingly. – Ritesh Gune Apr 08 '14 at 04:01
  • @RiteshGune last question why do i get error in getDefaultSharedPreferences() do i have to add more code? – Giant Apr 08 '14 at 04:08
  • this is the error "The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments ()" and i change this saveCheckBoxState(boolean); to this saveCheckBoxState(isChecked); – Giant Apr 08 '14 at 04:18
  • Sry my mistake, you need to pass context in getDefaultSharedPreferences. I have edited my answer with the correction. – Ritesh Gune Apr 08 '14 at 04:21
  • i dont mean to take much of your time but i get 3 error from that code one is saveCheckBoxState(boolean);->The method saveCheckBoxState(Context, boolean) in the type Login is not applicable for the arguments () 2nd is getCheckBoxState(Context context)->This method must return a result of type boolean 3rd is getCheckBoxState->The method getCheckBoxState(Context) in the type Login is not applicable for the arguments () – Giant Apr 08 '14 at 05:20
  • plz check the updated answer, using getApplicationContext() for context and added the word return which was missing in getCheckBoxState() – Ritesh Gune Apr 08 '14 at 05:32
1

You should persist the checkbox state. For example, you can use SharedPreferences.

cybersam
  • 63,203
  • 6
  • 53
  • 76
  • i have a question.i am not familiar with sharedpreferences and i am using an sqlite database in this app for storing data.is it ok to use sqlite database and sharepreference in one app?and can you give me sample?:) – Giant Apr 08 '14 at 03:40
  • 1
    You can use both. Or, you can store the checkbox state in the sqlite DB since you already have that. – cybersam Apr 08 '14 at 03:42
1

You need to store the check state in some sort of persistent storage. The simplest would be to use SharedPreferences. You'd store the value in your listener and read it in onResume.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • i have a question.i am not familiar with sharedpreferences and i am using an sqlite database in this app for storing data.is it ok to use sqlite database and sharepreference in one app?and can you give me sample?:) – Giant Apr 08 '14 at 03:40
  • 1
    You can use both. Or, you can store the checkbox state in the sqlite DB since you already have that. – cybersam Apr 08 '14 at 03:41
  • 1
    @HakHak - There's no problem at all using both `SharedPreferences` and sqlite in the same app. The framework handles them independently of one another. Or you can do as cybersam suggests and add a table to your db to persist the check state (and possibly other values). – Ted Hopp Apr 08 '14 at 03:45
0
     CheckBox stayInCheckBox = (CheckBox) findViewById(R.id.check_remember);
 SharedPreferences sharedpreferences = PreferenceManager  .getDefaultSharedPreferences(getApplicationContext());


// put this code in oncreate method 
public void stayIn()
{
    sharedpreferences = getSharedPreferences("myrem", MODE_PRIVATE);
    String s3 = sharedpreferences.getString("check", "false");

    String name = sharedpreferences.getString("name", null);


    if (s3.equals("true")) {
        stayInCheckBox.setChecked(true);
        editUser.setText(name);
        editPassword.setText(pass);
    } else {
        stayInCheckBox.setChecked(false);
    }
}

// put this code when app is closed

public void setSharedPreference() 
{
    if (stayInCheckBox.isChecked()) {
        String s1 = "true";
        sharedpreferences = getSharedPreferences("myrem", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("name", editUser.getText().toString());
        editor.putString("check", s1);
        editor.commit();
    } else {
        String s2 = "false";
        sharedpreferences = getSharedPreferences("myrem", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedpreferences.edit();
        editor.putString("check", s2);
        editor.commit();
    }
}
Nilesh Patel
  • 137
  • 6
0

Use Shared Preferences for "remember me" functionality, just set Boolean value to true if checkbox is checked else false.

Please refer below link for Shared Preferences:-

Get Android shared preferences value in activity/normal class

Rahul Sharma
  • 121
  • 1
  • 8