Junior — Middle
Why is implementing the Parcelable interface necessary in Android objects?
sobes.tech AI
Answer from AI
The Parcelable interface in Android is used for efficient serialization of objects so that they can be transferred between application components (for example, between Activity or Service) via Intent or to save state.
The need to implement Parcelable instead of standard serialization (Serializable) is due to:
- Performance:
Parcelableworks faster and requires fewer resources because it is optimized for Android. - Control: the developer explicitly describes how the object is serialized and deserialized, which reduces errors and increases efficiency.
A simple implementation example:
public class User implements Parcelable {
private String name;
private int age;
protected User(Parcel in) {
name = in.readString();
age = in.readInt();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel in) {
return new User(in);
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}
Thus, Parcelable provides an efficient mechanism for data transfer between Android components.