Saving Android Activity state using Save Instance State -


i've been working on android sdk platform, , little unclear how save application's state. given minor re-tooling of 'hello, android' example:

package com.android.hello;  import android.app.activity; import android.os.bundle; import android.widget.textview;  public class helloandroid extends activity {    private textview mtextview = null;    /** called when activity first created. */   @override   public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);      mtextview = new textview(this);      if (savedinstancestate == null) {        mtextview.settext("welcome helloandroid!");     } else {        mtextview.settext("welcome back.");     }      setcontentview(mtextview);   } } 

i thought enough simplest case, responds first message, no matter how navigate away app.

i'm sure solution simple overriding onpause or that, i've been poking away in documentation 30 minutes or , haven't found obvious.

you need override onsaveinstancestate(bundle savedinstancestate) , write application state values want change bundle parameter this:

@override public void onsaveinstancestate(bundle savedinstancestate) {   super.onsaveinstancestate(savedinstancestate);   // save ui state changes savedinstancestate.   // bundle passed oncreate if process   // killed , restarted.   savedinstancestate.putboolean("myboolean", true);   savedinstancestate.putdouble("mydouble", 1.9);   savedinstancestate.putint("myint", 1);   savedinstancestate.putstring("mystring", "welcome android");   // etc. } 

the bundle way of storing nvp ("name-value pair") map, , passed in oncreate() , onrestoreinstancestate() you'd extract values this:

@override public void onrestoreinstancestate(bundle savedinstancestate) {   super.onrestoreinstancestate(savedinstancestate);   // restore ui state savedinstancestate.   // bundle has been passed oncreate.   boolean myboolean = savedinstancestate.getboolean("myboolean");   double mydouble = savedinstancestate.getdouble("mydouble");   int myint = savedinstancestate.getint("myint");   string mystring = savedinstancestate.getstring("mystring"); } 

you use technique store instance values application (selections, unsaved text, etc.).


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -