Sharedpreferences toggle state?

98 views Asked by At

I have a toggle that change the brightness in my device from manual to authomatic. It works but the state of button doesn't save.. There are two things i need right now.

1) Save the button state using sharedpreferences 2) Check when i open the application which kind of brightness there is in the phone.

This is the toggle in my onCreate:

autoBrightToggle = (ToggleButton)v.findViewById(R.id.luminosita);
        autoBrightToggle.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (autoBrightToggle.isChecked()) {
                    setAutoBrightness(true);
                } else {
                    setAutoBrightness(false);
                }
            }
        }); 

and the method:

void setAutoBrightness(boolean value) {
                if (value) {
                    Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
                } else {
                    Settings.System.putInt(getActivity().getContentResolver(), SCREEN_BRIGHTNESS_MODE, SCREEN_BRIGHTNESS_MODE_MANUAL);
                }
            }

i tryied in this way but not works:

sPrefdata  = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); 
        ToggleButton autoBrightToggle = (ToggleButton) findViewById(R.id.brightoggle); //Dichiaro il toggle
        boolean togglebrightness = sPrefdata.getBoolean("DATA", false);  a
            if (togglebrightness ) //if (tgpref) may be enough, not sure
            {

                autoBrightToggle .setChecked(true);
            }
                else
            {
                autoBrightToggle .setChecked(false);
            }

and so in the onClick

SharedPreferences sPref = getSharedPreferences(PREFS_NAME, 0);
            Editor editor = sPref.edit();
            editor.putBoolean("DATA", true); //or false 
            editor.apply();

but doesn't work. Doesn't save the state and the method stops works. How can i solve? And how can i check which is the actual brightness?

1

There are 1 answers

1
Naeem A. Malik On

Try the snippet given below, I've used it to save strings in shared preferences.

SharedPreferences.Editor ed = getSharedPreferences("DATA", 0).edit();
ed.putBoolean("DATA", true);
ed.commit();