Junior — Middle
Are there classes or objects in your experience capable of saving their state as a byte sequence for later recovery?
sobes.tech AI
Answer from AI
In Android, the following mechanisms are often used to save and restore the state of objects:
-
Parcelable: an interface that allows objects to be serialized into a byte sequence (Parcel) and restored from it. Used for passing data between components (e.g., between Activities).
-
Serializable: a standard Java interface for serializing objects. Less efficient compared to Parcelable but easier to use.
-
Bundle: a container for storing key-value pairs, which can contain objects implementing Parcelable or Serializable.
Example implementation of Parcelable:
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];
}
};
}