0

I am using Toggle button and now i have to control on state of it when switching between activities and i am able to control the state as well, but even toggle state is off it still performing toggle on tasks

    boolean tg1pref;
    public SharedPreferences preferences;

    toggleMap = (ToggleButton) findViewById(R.id.toggleMap);
    toggleMap.setOnCheckedChangeListener(this);

        preferences = getApplicationContext().getSharedPreferences("tg1pref",0);

        tg1pref = preferences.getBoolean("tg1pref", true);
        if (tg1pref) {
            toggleMap.setChecked(true);
        } else {
            toggleMap.setChecked(false);
        }

    ...........
    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {      

        if(isChecked)
        {   
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tg1pref", true); // value to store
            editor.commit();

            cd = new ConnectionDetector(getApplicationContext());
            // Check for internet connection
            if (!cd.isConnectingToInternet()) {
                // Internet Connection is not present
                alert.showAlertDialog(PunchInActivity.this, "Internet not available",
                        "Please connect to working Internet connection", false);
                // stop executing code by return
                return;
            }
            else 
            {                                    
                startTimer();   
            }

        } else 
        {               
            SharedPreferences.Editor editor = preferences.edit();
            editor.putBoolean("tg1pref", false); // value to store
            editor.commit();
        }
}
Sun
  • 6,768
  • 25
  • 76
  • 131

2 Answers2

0
tg1pref = preferences.getBoolean("tg1pref", true);

use false instead of true in above line. That should work.

Vilas
  • 1,695
  • 1
  • 13
  • 13
0

I resolved my issue own, by moving code in onResume()

@Override
        protected void onResume() {
            super.onResume();

            tg1pref = preferences.getBoolean("tg1pref", true);
            if (tg1pref) {
                toggleMap.setChecked(true);
            } else {
                toggleMap.setChecked(false);
            }
        }
Sun
  • 6,768
  • 25
  • 76
  • 131