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.
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.
This question is related to
android
android-activity
onactivityresult
Your error is in resultCode = Activity.RESULT_CANCELED
, you should instance like resultCode == Activity.RESULT_CANCELED
==
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
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)
.
Source: Stackoverflow.com