Jacob Jones Jacob Jones - 14 days ago 6
Android Question

Android return object as a activity result

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

Answer

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(null);
resultIntent.putExtra("STRING_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 = data.getExtras().getSerializable("STRING_GOES_HERE");
    }

    ...
}

You can read about the methods on the Activity javadoc page.

Comments