How to Send an Object from One Android Activity to Another Using Intents
Updated 5/22/2024
Passing data between activities in Android is a common task, especially when dealing with complex objects. This guide will explain the best practices for sending an object of a custom type from one Activity to another using the putExtra() method of the Intent class.
Using Parcelable
The recommended way to pass objects between activities is by implementing the Parcelable interface. This method is preferred because it is much faster than Java’s native serialization.
Step-by-Step Implementation
Create a Parcelable Class: Implement the Parcelable interface in your class.
public class MyParcelable implements Parcelable {
private int mData;
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Put the Parcelable Object in the Intent: Use the putExtra() method to add your Parcelable object to the Intent.
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra("my_parcelable", myParcelableObject);
startActivity(intent);
Retrieve the Parcelable Object: In the receiving activity, use the getParcelableExtra() method to retrieve your object.
Choosing the right method depends on your specific requirements. Parcelable is generally the best choice for its performance, but Serializable and JSON with GSON are also viable options, especially for simpler use cases.
Automating Your Tests with Repeato
While developing and testing your Android applications, consider using Repeato, a No-code test automation tool for iOS and Android. Repeato allows you to create, run, and maintain automated tests for your apps quickly and efficiently, leveraging computer vision and AI. This tool is particularly beneficial for mobile developers as it helps to focus on creating a great product without getting bogged down by the complexities of test automation. Non-technical colleagues or QAs can also handle test automation tasks, streamlining the workflow even further.
For more detailed guides and documentation, visit our documentation page.