Sobes.tech
Junior — Middle

How is serialization and deserialization of objects performed using Parcelable in Android?

sobes.tech AI

Answer from AI

In Android, the Parcelable interface is used for efficient serialization of objects to pass them between components (for example, between Activities via Intent).

Serialization (writing an object):

  • The class must implement the Parcelable interface.
  • Override the writeToParcel(Parcel dest, int flags) method, where you write all the object's fields to the Parcel using methods like writeInt(), writeString(), etc.

Deserialization (reading an object):

  • Create a static field CREATOR of type Parcelable.Creator<T>, which implements the methods:
    • createFromParcel(Parcel in) — reads data from the Parcel and creates an object.
    • newArray(int size) — creates an array of objects.
  • In the constructor that takes a Parcel, read the fields in the same order they were written.

Example:

class User(val name: String, val age: Int) : Parcelable {
    constructor(parcel: Parcel) : this(
        parcel.readString() ?: "",
        parcel.readInt()
    )

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(name)
        parcel.writeInt(age)
    }

    override fun describeContents() = 0

    companion object CREATOR : Parcelable.Creator<User> {
        override fun createFromParcel(parcel: Parcel) = User(parcel)
        override fun newArray(size: Int) = arrayOfNulls<User?>(size)
    }
}

Thus, the object can be passed via Intent:

intent.putExtra("user", user)

and retrieved:

val user = intent.getParcelableExtra<User>("user")
How is serialization and deserialization of objects… - sobes.tech