Android return object as a activity result
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.
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.