Sobes.tech
Junior

What are serializable and parcelable objects?

sobes.tech AI

Answer from AI

Serializable objects can be converted into a byte stream for storage or transmission using Java's standard mechanism java.io.Serializable.

Parcelable objects can also be packaged and unpacked, but they use a specialized Android mechanism android.os.Parcelable. This mechanism is more efficient for passing data between Android components because it is optimized for IPC (Inter-Process Communication).

Feature Serializable Parcelable
Mechanism Java reflection Android Parceling API
Performance Less efficient (uses reflection) More efficient
Implementation Simpler (marker interface) Requires implementing writeToParcel, createFromParcel, describeContents methods
Usage Standard Java applications, remote method invocation (RMI) Android-specific, passing data between activities, services, etc.
Boilerplate Less code More code

Example implementation of Parcelable:

// MyParcelableObject.java
package com.example.myapplication;

import android.os.Parcel;
import android.os.Parcelable;

public class MyParcelableObject implements Parcelable {
    private String name;
    private int value;

    public MyParcelableObject(String name, int value) {
        this.name = name;
        this.value = value;
    }

    protected MyParcelableObject(Parcel in) {
        name = in.readString();
        value = in.readInt();
    }

    public static final Creator<MyParcelableObject> CREATOR = new Creator<MyParcelableObject>() {
        @Override
        public MyParcelableObject createFromParcel(Parcel in) {
            return new MyParcelableObject(in);
        }

        @Override
        public MyParcelableObject[] newArray(int size) {
            return new MyParcelableObject[size];
        }
    };

    @Override
    public int describeContents() {
        return 0; // Usually 0 unless special file descriptors
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(name);
        dest.writeInt(value);
    }

    // Getters (omitted for brevity)
}