android - Accessing instance of the parent activity? -


suppose have class first.java(activity class) , start activity in class (second.java - activity class). how can access instance of first.java second.java ? can give me explanation on this.. example great...

if need second activity return data first activity recommend use startactivityforresult() start second activity. in onresult() in first activity can work needed.

in first.java start second.java:

intent intent = new intent(this, second.class); int requestcode = 1; // or number choose startactivityforresult(intent, requestcode); 

the result method:

protected void onactivityresult (int requestcode, int resultcode, intent data) {   // collect data intent , use   string value = data.getstring("somevalue"); } 

in second.java:

intent intent = new intent(); intent.putextra("somevalue", "data"); setresult(result_ok, intent); finish(); 

if not wish wait second activity end before work in first activity, instead send broadcast first activity reacts to.

edit:

if need access values in first activity without making static reference it, consider putting activities in activitygroup.

so, activitygroup starts first activity. , first activity uses activitygroup start second activity. have access first activity through call getparent() in second activity.

class myactivitygroup extends activitygroup {   @override   public void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     startchildactivity("first", new intent(this, first.class));   }   public void startchildactivity(intent intent) {     window window = getlocalactivitymanager().startactivity(id, intent);       if (window != null) {         setcontentview(window.getdecorview());     }   } } 

in first.class:

intent = new intent(this, second.class); ((myactivitygroup) getparent()).startchildactivity("second", intent); 

in second.class:

activity first = (first) getparent(); 

Comments

Popular posts from this blog

python - Scipy curvefit RuntimeError:Optimal parameters not found: Number of calls to function has reached maxfev = 1000 -

c# - How to add a new treeview at the selected node? -

java - netbeans "Please wait - classpath scanning in progress..." -