Junior — Middle
Explain what the Parcelable interface is and what it is used for in Android development.
sobes.tech AI
Answer from AI
The Parcelable interface in Android is used for efficient serialization of objects to pass them between application components, such as between Activity or Fragment. Unlike the standard Serializable, Parcelable is optimized for Android and works faster because it implements its own mechanism for packing and unpacking data.
To make a class Parcelable, you need to implement the writeToParcel() method to write data into a Parcel and a constructor that restores the object from a Parcel. Additionally, a static CREATOR field must be created, which helps the system create objects from a Parcel.
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(): Int = 0
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel): User = User(parcel)
override fun newArray(size: Int): Array<User?> = arrayOfNulls(size)
}
}
Thus, Parcelable allows for fast and efficient transfer of complex objects between Android application components.