I am following a tutorial that uses “startActivityForResult” function. I know why this function is used and if we want to use the returned data, we use onActivityResult() function. The thing that I wana know is, why do we pass an Integer to startActivityForResult() function? And where is it used?
Thanks for your kind help!
When the Activity that you’re starting finished, that second argument is passed to the method
onActivityResult()of the calling Activity. This is to distinguish different results from one another.You may have a case where an Activity needs to call several others for results, and by specifying a unique
intfor each of them, you can determine the correct thing to do when you get a result.Edit: Here’s an example.
Suppose you have a screen (Activity A) where you choose a picture from your gallery, and you choose a friend to send it to. You’ll start an activity to pick a picture from the gallery on a button click, and maybe you also have a “friend picker” activity which you can also start from Activity A.
You want both of those activities to return the data the user selected.
onActivityResult()will get called on Activity A when the user finishes with the two activities described above. By specifying therequestCodeforstartActivityForResult()for the gallery activity, and your “friend picker”, you know what to do inonActivityResult().Also, note that you don’t need a complicated scheme for
requestCode. You could just pass in the values1and2for the gallery and friend picker, respectively.