android - How to save the togglebutton state on backpressed -


i want save state of togglebutton service can run checking state of togglebutton while activity not active. coding of activity class. in whatever user save togglebtn service must run per that.

public class mainactivity extends activity implements onclicklistener {      togglebutton tgl;      @override     protected void oncreate(bundle savedinstancestate) {         super.oncreate(savedinstancestate);         setcontentview(r.layout.activity_main);         tgl=(togglebutton)findviewbyid(r.id.togglebutton1);         tgl.setonclicklistener(this);     }      @override     public boolean oncreateoptionsmenu(menu menu) {         // inflate menu; adds items action bar if present.         getmenuinflater().inflate(r.menu.main, menu);         return true;     }      @override     public void onclick(view arg0) {         // todo auto-generated method stub         if(tgl.ischecked()){             intent i=new intent(mainactivity.this,run.class);             startservice(i);         }else{          }     }     @override     public void onbackpressed() {         // todo auto-generated method stub         if(tgl.ischecked()){             tgl.setchecked(true);         }else{          }          super.onbackpressed();     }  } 

i suggest keep state of toggle button preferences , retrieve them when need it(here on press). hope idea following code:

to save:

@override public void onclick(view v)  {     if (toggle.ischecked())      {         sharedpreferences.editor editor = getsharedpreferences("com.example.xyz", mode_private).edit();         editor.putboolean("nameofthingtosave", true);         editor.commit();     }     else     {         sharedpreferences.editor editor = getsharedpreferences("com.example.xyz", mode_private).edit();         editor.putboolean("nameofthingtosave", false);         editor.commit();     } } 

to load:

@override protected void oncreate(bundle savedinstancestate)  {     sharedpreferences sharedprefs = getsharedpreferences("com.example.xyle", mode_private);     toggle.setchecked(sharedprefs.getboolean("nameofthingtosave", true)); } 

Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -