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
Parcelableinterface. - Override the
writeToParcel(Parcel dest, int flags)method, where you write all the object's fields to theParcelusing methods likewriteInt(),writeString(), etc.
Deserialization (reading an object):
- Create a static field
CREATORof typeParcelable.Creator<T>, which implements the methods:createFromParcel(Parcel in)— reads data from theParceland 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")