0

I am trying to implement the switch widget in Android. However whenever I set the switch to 'OFF' position and I close and re-open my application, it again sets itself to 'ON' value. How can I make it set itself according to the user.

TechFrk
  • 185
  • 2
  • 2
  • 15

1 Answers1

0

My SettingScreen,java

 toggleCamera = (ToggleButton) findViewById(R.id.toggleCamera);
            Boolean b = AppTypeDetails.getInstance(SettingScreen.this).getToggleStatus();
            toggleCamera.setChecked(b);
            toggleCamera.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (toggleCamera.isChecked()) {
                        AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(true);
                    } else {
                        AppTypeDetails.getInstance(SettingScreen.this).setToggleStatus(false);
                    }
                }
            });

AppTypeDetails.java

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class AppTypeDetails {

    private SharedPreferences sh;

    private AppTypeDetails() {

    }

    private AppTypeDetails(Context mContext) {
        sh = PreferenceManager.getDefaultSharedPreferences(mContext);
    }

    private static AppTypeDetails instance = null;

    public synchronized static AppTypeDetails getInstance(Context mContext) {
        if (instance == null) {
            instance = new AppTypeDetails(mContext);
        }
        return instance;
    }



    // get toggle Status
    public boolean getToggleStatus() {
        return sh.getBoolean("ToggleButton", false);
    }

    public void setToggleStatus(Boolean toggle) {
        sh.edit().putBoolean("ToggleButton", toggle).commit();
    }



    public void clear() {
        sh.edit().clear().commit();
    }

}

This will successfully worked...

Chirag Savsani
  • 6,020
  • 4
  • 38
  • 74
  • Why would you use a 'singleton' just to access `SharedPreferences`? – Squonk Mar 28 '15 at 08:01
  • @Squonk In my application I use SharedPreferences many times and I store Email,User Name, Map Type, ToggleButton and many more... in SharedPreferences. – Chirag Savsani Mar 28 '15 at 08:20
  • I'm not questioning the use of `SharedPreferences` - what I was asking is why you'd use a 'singleton' (as a wrapper) in order to do so? – Squonk Mar 28 '15 at 08:20
  • @Squonk I use singleton because I want to set some global configuration when Application is Start.. – Chirag Savsani Mar 28 '15 at 08:39
  • @Squonk this is not proper way?? – Chirag Savsani Mar 28 '15 at 08:42
  • I just think it is unnecessary especially for saving state of UI components. Access to `SharedPreferences` should be possible from any Android class which handles UI elements anyway. – Squonk Mar 28 '15 at 09:29