Skip to content Skip to sidebar Skip to footer

How To Store Toogle Button Status In Shared Preference And Load The Status Later In Android?

The thing is I want to store my toogle button status in shared preference, so that I when I return to the application my toogle button wil stay in previous state. This is kind of s

Solution 1:

you can use SharedPreferences to store state of your ToggleButton

The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

Sample code

SharedPreferences sp=getSharedPreferences("Login", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit()

tb_vibrate = (ToggleButton)this.findViewById(R.id.tb_vibrate);
tb_vibrate.setOnClickListener(newView.OnClickListener() {

        @OverridepublicvoidonClick(View v) {

            if(tb_vibrate.isChecked())
            {
                Toast.makeText(ProfileActivity.this, "Toggle button is on", Toast.LENGTH_LONG).show();
                tb_vibrate.setChecked(true);

                Ed.putBoolean("ISCHECKED",true);
                Ed.commit();

            }
            else {
                Toast.makeText(ProfileActivity.this, "Toggle button is Off", Toast.LENGTH_LONG).show();
                tb_vibrate.setChecked(false);
                Ed.putBoolean("ISCHECKED",false);
                Ed.commit();
            }
        }
    });

getting values use the below code

SharedPreferencespreferences= getSharedPreferences("MyPrefs", MODE_PRIVATE);
 booleanflag= preferences.getBoolean("ISCHECKED", false);
 if(flag){
        tb_vibrate.setChecked(true);
    }else {
        tb_vibrate.setChecked(false);
    }

Post a Comment for "How To Store Toogle Button Status In Shared Preference And Load The Status Later In Android?"