By Hesam


2012-05-02 03:03:00 8 Comments

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?

8 comments

@Nishant 2012-05-02 03:36:38

From your FirstActivity call the SecondActivity using startActivityForResult() method

For example:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.

For example: In SecondActivity if you want to send back data:

Intent returnIntent = new Intent();
returnIntent.putExtra("result",result);
setResult(Activity.RESULT_OK,returnIntent);
finish();

If you don't want to return data:

Intent returnIntent = new Intent();
setResult(Activity.RESULT_CANCELED, returnIntent);
finish();

Now in your FirstActivity class write following code for the onActivityResult() method.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if(resultCode == Activity.RESULT_OK){
            String result=data.getStringExtra("result");
        }
        if (resultCode == Activity.RESULT_CANCELED) {
            //Write your code if there's no result
        }
    }
}//onActivityResult

@ismail 2013-10-30 23:05:45

What is the purpose of putting an intent when RESUT_CANCELLED in setResult(RESULT_CANCELED, returnIntent);

@Nishant 2013-10-31 04:42:00

@ismail Suppose in the SecondActivity some exception occurred, in that case also you need to return the result to the FirstActivity,so you can set the result as "RESULT_CANCELLED" in the catch block and return to FirstActivty and in FirstActivity's' 'onActivityResult() you can check whether you got the success or failure result.

@ismail 2013-10-31 10:43:10

So it's up to you, if you don't need to know the reason for cancelling, you can use just setResult(RESULT_CANCELED); without any intent

@Francisco Corrales Morales 2014-05-09 14:23:53

can I do this in an AsynkTask as the SecondActivity?,

@Nishant 2014-05-17 19:49:44

@FranciscoCorrales If you have to start SecondActivity from AsyncTask, Yes you can do this.

@Shafi 2014-09-15 09:45:57

@Nishant How to implement the same thing in fragments instead of activity?

@Nishant 2014-09-20 16:43:00

@Shafi there is no concept of onActivityResult() call back for fragments as fragments basically are the part of a single Activity.If you want to communicate between two fragments you can see this link developer.android.com/training/basics/fragments/…

@Lei Leyba 2014-09-30 05:49:35

finish isn't called after startActivityForResult?

@Nishant 2014-10-01 06:26:59

@Lei Leyba No finish() is not called after calling startActivityForResult().First Actvity will move to pause state.

@Martin Pfeffer 2015-03-09 21:51:56

For me it is not working -.- this is what I hate soooo much about Android - this system is so unreliable :-/

@AlexioVay 2017-04-13 11:03:50

There's nothing "unreliable" when you just don't understand this simple code explanation

@Ruslan Berozov 2017-06-01 15:06:52

What happens if we have three or more actvities? I have a problem with it now. I need to return to first activity from third through second, but I loss data in onActivityResult(...) in first activity after this and resultCode = CANCELED...

@spydon 2017-08-07 23:03:14

You can use setResult(RESULT_OK); for example directly before calling finish(); without creating a new intent in newer versions of android.

@Damir Varevac 2018-07-08 08:58:32

Works perfectly for some simple use cases.

@Rohit Singh 2017-12-22 09:54:47

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)

1) startActivity B

Intent i = new Intent(A.this, B.class);
startActivity(i);

2) Set requested data

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

b1......clickListener
{
   Intent resultIntent = new Intent();
   resultIntent.putExtra("Your_key","Your_value");
   setResult(RES_CODE_A,resultIntent);
   finish();
}

Not sending data

b2......clickListener
    {
       setResult(RES_CODE_B,new Intent());
       finish();
    }

user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code

3) Retrieve result

For that override onActivityResult method

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);

if (resultCode == RES_CODE_A) {

     // b1 was clicked 
   String x = data.getStringExtra("RES_CODE_A");

}
else if(resultCode == RES_CODE_B){

   // b2 was clicked

}
else{
   // back button clicked 
}
}

@Suragch 2016-12-05 08:36:32

Example

To see the entire process in context, here is a supplemental answer. See my fuller answer for more explanation.

enter image description here

MainActivity.java

public class MainActivity extends AppCompatActivity {

    // Add a different request code for every activity you are starting from here
    private static final int SECOND_ACTIVITY_REQUEST_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        startActivityForResult(intent, SECOND_ACTIVITY_REQUEST_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) { // Activity.RESULT_OK

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.java

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

@Jerry Abraham 2018-10-25 10:21:13

Can this done by two different apps A and app b?stackoverflow.com/questions/52975645/…

@Tomasz Mularczyk 2015-10-23 12:58:55

For those who have problem with wrong requestCode in onActivityResult

If you are calling startActivityForResult() from your Fragment, 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);

@Julian Alberto Piovesan Ruiz D 2015-05-26 20:40:47

Complementing the answer from @Nishant,the best way to return the activity result is:

Intent returnIntent = getIntent();
returnIntent.putExtra("result",result);
setResult(RESULT_OK,returnIntent);
finish();

I was having problem with

new Intent();

Then I found out that the correct way is using

getIntent();

to get the current intent

@spaaarky21 2018-06-29 16:52:54

It feels a bit odd to create a new Intent that only exists to hold a Bundle and doesn't have the normal values like an action or component. But it also feels a bit odd (and potentially dangerous?) to modify the Intent that was used to launch the current activity. So I searched the source for Android itself and found that they always create a new Intent to use as the result. For example, github.com/aosp-mirror/platform_frameworks_base/blob/…

@Julian Alberto Piovesan Ruiz D 2018-06-29 18:29:55

Hello spaaarky21, thank you for your comment. I'm sorry I wasn't so clear in explaining exactly how I ended up with that solution. It was three years ago, and I can only remember that my app was crashing because of "new Intent", that's what I meant when I said "I was having problem with". Actually I just tryed with "getIntent", because it made sense at the time, and it worked! Because of it I decided to share my solution. Maybe not the best choise of words to say "best way" or "correct way", but I stand by my solution. It's what solved my problem and aparently of other people too. Thanks

@Julian Alberto Piovesan Ruiz D 2018-06-29 18:32:32

And I'm not actually modifying the Intent that was used to launch the current activity, I'm just adding an extra called "result"

@Dharmendra Pratap 2014-09-30 12:30:37

First you use startActivityForResult() with parameters in first Activity and if you want to send data from second Activity to first Activity then pass value using Intent with setResult() method and get that data inside onActivityResult() method in first Activity.

@Sam 2012-05-02 03:07:14

How to check the result from the main activity?

You need to override Activity.onActivityResult() then check its parameters:

  • requestCode identifies which app returned these results. This is defined by you when you call startActivityForResult().
  • resultCode informs you whether this app succeeded, failed, or something different
  • data holds any information returned by this app. This may be null.

@JCarlos 2017-08-11 23:32:13

It means that the requestCode is only used in the first activity, and it is never used for the 2nd activity? If the 2nd activity has different approaches, it would change, but based in the intent extras and not by the requestCode, right? Edit: Yes, stackoverflow.com/questions/5104269/…

@DaviF 2014-03-08 13:54:56

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:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_CANCELED) {
        return;
    }

    global_lat = data.getDoubleExtra("LATITUDE", 0);
    global_lng = data.getDoubleExtra("LONGITUDE", 0);
    new_latlng = true;
}

@Override
protected void onResume() {
    super.onResume();

    if(new_latlng)
    {
        PhysicalTagProperties.this.setLocation(global_lat, global_lng);
        new_latlng=false;
    }
}

This seems silly but works pretty well.

Related Questions

Sponsored Content

87 Answered Questions

[SOLVED] Close/hide the Android Soft Keyboard

26 Answered Questions

34 Answered Questions

46 Answered Questions

28 Answered Questions

[SOLVED] What is 'Context' on Android?

41 Answered Questions

[SOLVED] Is there a unique Android device ID?

13 Answered Questions

[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

25 Answered Questions

[SOLVED] Is there a way to run Python on Android?

77 Answered Questions

31 Answered Questions

[SOLVED] Activity restart on rotation Android

Sponsored Content