Explain Codes LogoExplain Codes Logo

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

java
parcelable
serialization
gson
Nikita BarsukovbyNikita Barsukov·Feb 19, 2025
⚡TLDR

To pass an object between Activities in Android, Intents with Serializable or Parcelable gets the job done:

First Activity(Launching):

Intent intent = new Intent(this, SecondActivity.class); intent.putExtra("spotTheDifference", objectToPass); // objectToPass mimics a chameleon with Serializable startActivity(intent);

Second Activity(Receiving):

YourClass objectToPass = (YourClass) getIntent().getSerializableExtra("spotTheDifference");

Now, Serializable might give you the "yay, I did it!" moments. But for performance-oriented folks, Parcelable is the way to go.

Dressing your object in Parcelable

Parcelable is the "fast and furious" of Android. It's speedier and optimized for inter-process communication on Android.

To pimp your object into a Parcelable:

  1. Implement Parcelable in your class. This isn't as terrifying as it sounds.
  2. Make your data see the parcel inside writeToParcel.
  3. Cook up a CREATOR to make new instances of your Parcelable class from the parcel.

Isaac Newton once said: "I can calculate the motion of heavenly bodies but not the madness of Java." Here's the blueprint to tame the beast:

public class FastAndFurious implements Parcelable { // Data fields here // Remember, less is more. And more less is, well, less @Override public void writeToParcel(Parcel parcel, int flags) { // You write, parcel reads! It's like a mini library in here } public static final Parcelable.Creator<FastAndFurious> CREATOR = new Parcelable.Creator<FastAndFurious>() { public FastAndFurious createFromParcel(Parcel in) { return new FastAndFurious(in); // a brand new FastAndFurious, just off the production line! } public FastAndFurious[] newArray(int size) { return new FastAndFurious[size]; // in case you want a whole fleet } }; }

To unbox it in the Second Activity, use getParcelableExtra:

FastAndFurious objectThatMovedFaster = getIntent().getParcelableExtra("spotTheDifference");

Giving Serializable a shot at nested complexity

Things get a little tricky with complex objects having nested structures. If you're a Serializable fanboy, remember that all nested classes must also be Serializable fans.

Give these tips a shot for better performance:

  • Keep your fields to primitives as much as possible: remember, simplicity is the ultimate sophistication.
  • Exclude fields from serialization with transient keyword: because sometimes, ignorance is indeed bliss!

Parcelable vs. Serializable: the face-off

Opt for Parcelable over Serializable — it's like choosing a sports car over a motorbike for a highway drive. Bumpy with Serializable but all smooth sailing with Parcelable!

Gson: your JSON serialization champ

Let's put Gson in the spotlight for data exchange between Activities:

  • Introduce Gson to your build.gradle:
implementation 'com.google.code.gson:gson:2.8.6'
  • Convert object to JSON, wrap it as a gift and send it to the next Activity:
Gson gson = new Gson(); String giftObject = gson.toJson(objectToPass); intent.putExtra("preservingTraditions", giftObject);
  • In the receiving Activity, unwrap the gift:
String giftObject = getIntent().getStringExtra("preservingTraditions"); RoleModel objectToPass = gson.fromJson(giftObject, RoleModel.class);

Remember, RoleModel.class is not RoleModel. Beware of the cloning machine! Also, don't lose sight of your data integrity during conversion.

When Serialization is too mainstream

Sometimes, serialization is like over-engineered toast. So, you might want to consider alternatives:

  1. Singleton pattern: Keep data in a singleton alive across the application.
  2. Application class: Extend Application for sharing data.

However, apply these sparingly! It could lead to time paradoxes (memory leak issues) and Skynet (hard to manage application states).

Ram, not the animal: saving memory

Transferring objects between Activities can be a memory-consuming affair. So strap in and:

  • Opt for smaller data types whenever possible.
  • Avoid large objects. Remember, size matters!
  • Clear references to objects from old Activities.

Bard of coding: writing robust code

For a really robust app:

  • Always check if Intent data is null, just as you check your parachute before a jump!
  • Use ProGuard. It's like your Swiss Army knife for obscure classes.
  • If you have unserializable objects, employ intermediate storage or custom wrappers.