Android: how to make an activity return results to the activity which calls it?
Asked Answered
U

5

166

I have a Location activity that can be called from many activities, such as Sign up and Order. In the Location activity the user enters his location, so the activity Location will return this new location to that activity which called it.

So when the Sign up activity calls the Location activity, it has to return the data to the Sign up activity. Another time the Order activity will do the same thing.

Note

I know you will tell me that I should post the code, but I am not asking you to give me the code; I just want some tips, links or good threads.

Unblinking answered 9/2, 2013 at 7:5 Comment(3)
you can used finish() call to back..Interfertile
Did you check StartActivityForResult developer.android.com/reference/android/app/Activity.htmlSartin
@Interfertile would you give me more details please, or if you have links that would be appreciatedUnblinking
A
305

In order to start an activity which should return result to the calling activity, you should do something like below. You should pass the requestcode as shown below in order to identify that you got the result from the activity you started.

startActivityForResult(new Intent(“YourFullyQualifiedClassName”),requestCode);

In the activity you can make use of setData() to return result.

Intent data = new Intent();
String text = "Result to be returned...."
//---set the data to pass back---
data.setData(Uri.parse(text));
setResult(RESULT_OK, data);
//---close the activity---
finish();

So then again in the first activity you write the below code in onActivityResult()

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String returnedResult = data.getData().toString();
            // OR
            // String returnedResult = data.getDataString();
        }
    }
}

EDIT based on your comment: If you want to return three strings, then follow this by making use of key/value pairs with intent instead of using Uri.

Intent data = new Intent();
data.putExtra("streetkey","streetname");
data.putExtra("citykey","cityname");
data.putExtra("homekey","homename");
setResult(RESULT_OK,data);
finish();

Get them in onActivityResult like below:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            String street = data.getStringExtra("streetkey");
            String city = data.getStringExtra("citykey");
            String home = data.getStringExtra("homekey");
        }
    }
}
Adamic answered 9/2, 2013 at 7:24 Comment(6)
what is you said ? i don't understand your last comment, sorry i am not good english, i am trying your code now, what is requestcode can i put any integer ?Unblinking
I said, No Problems(NP) and as you said you might be late in implementing this, I replied that to take your own time and then comment it so that I can get notified. Coming to requestcode, yes you can give an integer value like int requestCode = 1;Adamic
yes it is work right, i am accept your answer, thank you very mush , i want to aks you if there is a way so not just send string, i want to send 3 strings , like "city", "street", "home", there are a way to label the strings ?Unblinking
your answer is very excellent, if you want , edit the title so many users can search for itUnblinking
I was looking for how to create the intent: new Intent(this, OtherActivity.class); I can use this code in an Activity.Livengood
fwiw, onActivityResult is actually protected, not public 🤷🏻‍♂️still super helpful answer, thoughHardcore
K
45

UPDATE Feb. 2021

As in Activity v1.2.0 and Fragment v1.3.0, the new Activity Result APIs have been introduced.

The Activity Result APIs provide components for registering for a result, launching the result, and handling the result once it is dispatched by the system.

So there is no need of using startActivityForResult and onActivityResult anymore.

In order to use the new API, you need to create an ActivityResultLauncher in your origin Activity, specifying the callback that will be run when the destination Activity finishes and returns the desired data:

private val intentLauncher =
    registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->

        if (result.resultCode == Activity.RESULT_OK) {
            result.data?.getStringExtra("streetkey")
            result.data?.getStringExtra("citykey")
            result.data?.getStringExtra("homekey")
        }
    }

and then, launching your intent whenever you need to:

intentLauncher.launch(Intent(this, YourActivity::class.java))

And to return data from the destination Activity, you just have to add an intent with the values to return to the setResult() method:

val data = Intent()
data.putExtra("streetkey", "streetname")
data.putExtra("citykey", "cityname")
data.putExtra("homekey", "homename")

setResult(Activity.RESULT_OK, data)
finish()

For any additional information, please refer to Android Documentation

Kuehn answered 23/2, 2021 at 13:34 Comment(1)
for this you will have to add this dependency implementation 'androidx.fragment:fragment-ktx:1.3.6'Warhol
C
5

If you want to finish and just add a resultCode (without data), you can call setResult(int resultCode) before finish().

For example:

...
if (everything_OK) {
    setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
    finish();
}
else {
   setResult(Activity.RESULT_CANCELED); // some error ...
   finish();
}
...

Then in your calling activity, check the resultCode, to see if we're OK.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == someCustomRequestCode) {
        if (resultCode == Activity.RESULT_OK) {
            // OK!
        }
        else if (resultCode = Activity.RESULT_CANCELED) {
            // something went wrong :-(
        }
    }
}

Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode).

Cotoneaster answered 1/8, 2017 at 12:13 Comment(1)
the value of Activity.RESULT_OK is actually -1, in case that confuses someone. I would just suggest using the Activity constantsReplevy
S
1

Your error is in resultCode = Activity.RESULT_CANCELED, you should instance like resultCode == Activity.RESULT_CANCELED ==

Spinozism answered 3/12, 2020 at 15:47 Comment(1)
Your answer may be helpful, but it is unclear where it is directed since the OP did not post any code. If you are commenting on another answer, you should direct your comments to the comment section of that answer.Whitehouse
B
-1

O,
in my case, i was calling finish() in recycler adapter (on item click).
and it was being called before setResult(CODE, intent);

if all the above fails,
comment the "finish();" and check where is "finish();" being called from somewhere else;

Brickkiln answered 6/3, 2023 at 6:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.