In my activity, I'm calling a second activity from the main activity by startActivityForResult
. In my second activity there are some methods that finish this activity (maybe without result), however, just one of them return a result.
For example, from the main activity I call a second one. In this activity I'm checking some features of handset such as does it have a camera. If it doesn't have then I'll close this activity. Also, during preparation of MediaRecorder
or MediaPlayer
if a problem happens then I'll close this activity.
If its device has a camera and recording is done completely, then after recording a video if a user clicks on the done button then I'll send the result (address of the recorded video) back to main activity.
How do I check the result from the main activity?
If you want to update the user interface with activity result, you can't to use
this.runOnUiThread(new Runnable() {}
Doing this the UI won't refresh with new value. Instead, you can do this:This seems silly but works pretty well.
For those who have problem with wrong requestCode in onActivityResult
If you are calling
startActivityForResult()
from yourFragment
, the requestCode is changed by the Activity that owns the Fragment.If you want to get the correct resultCode in your activity try this:
Change:
startActivityForResult(intent, 1);
To:getActivity().startActivityForResult(intent, 1);
Very common problem in android
It can be broken down into 3 Pieces
1 ) start Activity B (Happens in Activity A)
2 ) Set requested data (Happens in activity B)
3 ) Receive requested data (Happens in activity A)
In this part, you decide whether you want to send data back or not when a particular event occurs.
Eg: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A
Clicking on Button b2 does not send any data.
Sending data
Not sending data
user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code
For that override onActivityResult method
Example
To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.
MainActivity.java
SecondActivity.java
You need to override
Activity.onActivityResult()
then check its parameters:requestCode
identifies which app returned these results. This is defined by you when you callstartActivityForResult()
.resultCode
informs you whether this app succeeded, failed, or something differentdata
holds any information returned by this app. This may benull
.Complementing the answer from @Nishant,the best way to return the activity result is:
I was having problem with
Then I found out that the correct way is using
to get the current intent