Android Development
Activity Communication
Object Serialization
Android Intents
Mobile App Development

How to pass an object from one activity to another on Android

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Passing data between activities is a common task in Android development. Although Android provides several ways to pass data between activities, passing complex data structures like objects can be more involved than simply passing primitive data types due to serialization requirements. In this article, we'll explore various methods to pass objects between activities in Android, offering technical explanations and examples to ensure a thorough understanding.

Methods to Pass Objects Between Activities

1. Using Parcelable

The Parcelable interface is particularly optimized for Android. It allows objects to be serialized more efficiently than Serializable. Here's how you can implement it:

Implementation Steps

  1. Make Your Class Parcelable: Implement the Parcelable interface in your object class.
java
1public class User implements Parcelable {
2    private String name;
3    private int age;
4
5    public User(String name, int age) {
6        this.name = name;
7        this.age = age;
8    }
9
10    protected User(Parcel in) {
11        name = in.readString();
12        age = in.readInt();
13    }
14
15    public static final Creator<User> CREATOR = new Creator<User>() {
16        @Override
17        public User createFromParcel(Parcel in) {
18            return new User(in);
19        }
20
21        @Override
22        public User[] newArray(int size) {
23            return new User[size];
24        }
25    };
26
27    @Override
28    public int describeContents() {
29        return 0;
30    }
31
32    @Override
33    public void writeToParcel(Parcel dest, int flags) {
34        dest.writeString(name);
35        dest.writeInt(age);
36    }
37}
  1. Pass the Object: Add the Parcelable object to an Intent.
java
1Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
2User user = new User("John Doe", 25);
3intent.putExtra("user", user);
4startActivity(intent);
  1. Retrieve the Object: Retrieve the Parcable object in the target activity.
java
User user = getIntent().getParcelableExtra("user");

2. Using Serializable

While not as efficient as Parcelable, the Serializable interface is easier to implement:

Implementation Steps

  1. Implement Serializable: Your object class should implement Serializable.
java
1public class User implements Serializable {
2    private String name;
3    private int age;
4
5    // Constructor, getters, and setters
6}
  1. Pass the Object: Use Intent to pass the object to another activity.
java
1Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
2User user = new User("Jane Doe", 30);
3intent.putExtra("user", user);
4startActivity(intent);
  1. Retrieve the Object: Unwrap the bundled object in the target activity.
java
User user = (User) getIntent().getSerializableExtra("user");

3. Using a Static Helper

If you prefer to avoid Parcelable or Serializable, you can use a static helper class, but this approach has its caveat concerning data persistence across configuration changes.

Implementation Steps

  1. Create a Helper Class: Store a reference to the object.
java
1public class DataHolder {
2    private static User user;
3    
4    public static void setUser(User u) {
5        user = u;
6    }
7    public static User getUser() {
8        return user;
9    }
10}
  1. Pass the Object: Use the helper class to store the object before starting the activity.
java
DataHolder.setUser(new User("Emily Clark", 28));
Intent intent = new Intent(CurrentActivity.this, TargetActivity.class);
startActivity(intent);
  1. Retrieve the Object: Fetch the object in the targeted activity.
java
User user = DataHolder.getUser();

Comparison Table

MethodEfficiencySerializationUsage ComplexityIdeal Use Case
ParcelableHighYesModeratePassing data between activities efficiently
SerializableLowYesEasySimplicity and quick implementation
Static HelperMediumNoEasyWhen object persistence across states isn't needed

Additional Considerations

Choosing Between Parcelable and Serializable

  • Performance: Parcelable is generally faster because it's designed specifically for Android. Use it when performance is crucial.
  • Ease of Use: Serializable is simpler to implement, requiring less boilerplate code; therefore, use it for small data structures or when performance isn't an issue.

Handling Parcelable Exceptions

When implementing Parcelable, ensure that all fields are properly written to and read from the Parcel. Missing fields or mismatches can cause runtime crashes.

java
1// Correct parcel operations to avoid exceptions
2@Override
3public void writeToParcel(Parcel dest, int flags) {
4    dest.writeString(name);
5    dest.writeInt(age);
6}

Conclusion

Passing objects between activities in Android can be achieved using several methods, each with specific advantages and trade-offs. While Parcelable offers high performance, Serializable provides ease of use, and static helpers offer simplicity at the cost of persistence risks. Understanding these methods will allow you to choose the most appropriate solution based on the specific requirements of your application.


Course illustration
Course illustration

All Rights Reserved.