13

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'....

Jacob Jones
  • 501
  • 2
  • 6
  • 22

3 Answers3

29

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.

M. Jahedbozorgan
  • 6,914
  • 2
  • 46
  • 51
Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • Sorry, didn't think straight. You need to retrieve the bundle and then individual extra. I updated my answer (based on assumption that your object is Serializable) – Aleks G Nov 03 '14 at 21:56
  • Your `MyClass` class needs to `implement Serializable` in order for this to work. – Zapnologica Feb 16 '16 at 05:36
  • 1
    @Zapnologica did you read my previous comment? _based on assumption that your object is Serializable_ – Aleks G Feb 16 '16 at 07:30
  • it was clear, object must be Serializable, additionally, for cross apps, add the serialVersionUID field to match object versions. – Ninja Coding Aug 24 '16 at 18:28
4

Check out this answer, which explains how to use startActivityForResult and onActivityResult.

This same process can be used for any object that is Serializable or Parcelable. Thus, if myObject is a custom class you've created, you will need to implement one of these interfaces.

Community
  • 1
  • 1
bmat
  • 2,084
  • 18
  • 24
-1

You can use setResult(int) read the android activity reference , specifically starting activities and getting results.

Silent Ace
  • 299
  • 1
  • 6
  • 20