Parcelable in Android : Java and Kotlin
All my articles are available for free to read. Here’s the link to this one.
In Android, the `Parcelable` interface is used to serialize and deserialize custom objects so that they can be passed between components, such as activities, fragments, and services. By implementing the `Parcelable` interface, you define how your object can be serialized into a `Parcel` and reconstructed back from it.
The `Parcel` class is an optimized container for transmitting data across Android components. It provides methods to write and read data of various types, including primitive types, arrays, and objects.
To make an object parcelable, you need to follow these steps:
- Implement the `Parcelable` interface:
public class MyObject implements Parcelable {
// Class implementation
}
2. Implement the `describeContents()` method:
@Override
public int describeContents() {
return 0;
}
The `describeContents()` method should typically return 0, unless you have special requirements for the contents of the `Parcelable`.
3. Implement the `writeToParcel()` method:
@Override
public void writeToParcel(Parcel dest, int flags) {
// Write object properties to the parcel
}
In the `writeToParcel()` method, you need to write the object properties to the `Parcel` using the appropriate methods like `writeInt()`…