phnmnn phnmnn -3 years ago 149
Android Question

How to pass an origin object(NOT COPY) from one activity to another on Android

How to pass origin object from one activity to another on Android?

For sure, we can serialized (Serializable, Parcelable, to/from JSON) and pass a copy of the object's data and a new object having the same data could be created; but it will NOT have the same references.

Here is some solution:

Code for the first activity:

final Object objSent = new Object();
final Bundle bundle = new Bundle();
bundle.putBinder(OBJECT_KEY, new ObjectWrapperForBinder(objSent));
startActivity(new Intent(this, SecondActivity.class).putExtras(bundle));

Code for the second activity:

final Object objReceived = ((ObjectWrapperForBinder)getIntent().getExtras().getBinder(OBJECT_KEY)).getData();

but the minimum API Level required 18

Are there other ways?

Answer Source

SOLUTION: BundleCompat allows to use putBinder/getBinder for all Android versions.


final Bundle bundle = new Bundle();
BundleCompat.putBinder(bundle,KEY, new ObjectWrapperForBinder(callback));


object = ((ObjectWrapperForBinder)BundleCompat.getBinder(intent.getExtras(),KEY)).getData();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download