Is it possible to return object as a activity result from child activity to parent? Just something like:
Intent resultIntent = new Intent(null);
resultIntent.putExtra("STRING_GOES_HERE", myObject);
setResult(resultIntent);
finish();
If it is possible, how should I retrieve myObject
in parent activity?
I figured out, that to retrieve data I need to do something like this:
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE_CHILD) {
MyClass myObject = data.getExtra("STRING_GOES_HERE");
}
}
Thing is that I get error, that can not resolve method 'getExtra'....
You must call the second activity using the startActivityForResult method. In your second activity, when it is finished, you can execute the setResult method where basically you put the result information. Then, on your first activity, you override the onActivityResult method.
registerForActivityResult() takes an ActivityResultContract and an ActivityResultCallback and returns an ActivityResultLauncher which you'll use to launch the other activity. An ActivityResultContract defines the input type needed to produce a result along with the output type of the result.
Use startActivityforResult to start Activity B. Implement override onActivityResult(int, int, Intent) method in Activity A and setResult in ActivityB. Use startActivityforResult in Activity A to launch activity B and use @override onActivityResult(int, int, Intent) method in your activity A to get data from B Activity.
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.
You cannot return an object, but you can return an intent containing your objects (provided they are primitive types, Serializable or Parcelable).
In your child activity, the code will be something like:
int resultCode = ...;
Intent resultIntent = new Intent();
resultIntent.putExtra("KEY_GOES_HERE", myObject);
setResult(resultCode, resultIntent);
finish();
In your parent activity you'll need to start the child activity with startActivityForResult
:
public final static int REQ_CODE_CHILD = 1;
...
Intent child = new Intent(getPackageName(), "com.something.myapp.ChildActivity");
startActivityForResult(child, REQ_CODE_CHILD);
and then in the onActivityResult
, you'll have:
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if(requestCode == REQ_CODE_CHILD) {
MyClass myObject = (MyClass)data.getExtras().getSerializable("KEY_GOES_HERE");
}
...
}
You can read about the methods on the Activity javadoc page.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With