Retrieving data from a Sub-Activity back to your Main Activity
Problem:Your main activity needs to retrieve data from a sub activity.
Solution:Use startActivityForResult(), and onActivityResult() in the main activity, and setResult() in the sub-activity.
Discussion:In this example we return a string from a Sub-Activity (MySubActivity) back to the Main Activity (MyMainActivity).
The first step is to "push" data from MyMainActivity via the Intent mechanism.
The Main Activity's onActivityResult() gets called after MySubActivity.finish().
The retrieved value is technically an Intent, and so we could use it for more complex data (such as a '''uri''' to a google contact or something). However, in the above example code, we are only interested in a string value via Intent.getExtras().
The requestCode ('''MYREQUESTCODE''') is supposed to be unique, and might be useful later. ie. ''Activity.finishActivity( MYREQUESTCODE )''
The second major step is to "pull" data back from MySubActivity to MyMainActivity.
Once again, Intents are used as data (ie. '''"iData"''').
setResult() requires a result code such as '''RESULTOK'''.
finish() essentially pushes the result from setResult().
Technically, the data from MySubActivity doesn't get "pull"-ed until we're back on the other side with MyMainActivity. So arguably it is more similar to a 2nd "push".
We don't have to use a public static final String variable for our "extra" field name, but I thought it was good style.
Use Case (informal) ==
In my app, I have a ListActivity with a ContextMenu (user long presses a selection to do something), and I wanted to let the Main-Activity know which row the user had selected for the ContextMenu action ( atm, my app only has one action ). I ended up using intent extras to pass the selected row's index as a string back to the parent activity; From there I could just convert the index back to an int and use it to identify the user row selection via ArrayList.get( index ). This worked for me, however I am sure there is another/better way.
See Also:Also see [[How to push string-values using Intent.putExtra()]]
[http://androidforums.com/application-development/102689-startactivityforresult.html ResultCode "gotcha"]
[http://developer.android.com/guide/appendix/faq/commontasks.html#opennewscreen startActivityForResultExample ] (under "Returning a Result from a Screen")
[http://developer.android.com/reference/android/app/Activity.html#startActivityForResult(android.content.Intent, int) Activity.startActivityForResult()]
Downloads:(not handled yet)