Can I pass data through a new Activity?
In my Android app, I start a new activity with startActivityForResult()
. I get the 开发者_StackOverflow社区result in onActivityResult()
perfectly. My problem is that there is a small bit of data that I know before I start the activity and I need that value to be available in onActivityResult()
, too. I tried attaching it to my intent as an extra, but it wasn't attached to the intent that is available when the activity returns the result. I made it work by storing the data in a global variable, but I really don't like that approach. Is there a better, right way to pass data through an activity (instead of just to it)?
To use the requestCode as a way to send that data as suggested in the comments looks a bit like hack to me. This is not the intended use of that code, and in general using things in this manner means you'll end up in trouble later.
Why not just define your integer in your class, and save it there? Pseudocode:
class YourAcrivity extends Activity{
private int yourInt;
private function yourFunction(){
//set your int
yourInt = 11;
//call your activity
//startActivityForResult();
}
function onActivityResult(){
//use yourInt
}
}
You can use setResult(int,Intent) to give data back to onActivityResult(), passing in the same intent you were given (although some of it's properties, like the action or uri, will be useless).
You can use this to build up data between two activities, with one supplying the information it knows about and the other filing in the rest and returning when it is called.
精彩评论