Junior
What is serialization?
sobes.tech AI
Answer from AI
Serialization is the process of converting an object or data structure into a format that can be easily stored (for example, in a file, memory, database) or transmitted over a network. Deserialization is the reverse process.
In Android, serialization is often used for:
- Transferring data between Activities or Fragments using
IntentorBundle. - Saving the state of Views (for example, during screen rotation).
- Caching data.
- Exchanging data with remote servers (JSON, XML).
Main serialization mechanisms in Android:
Serializable: Easy to use, but slow and creates many temporary objects. It is part of standard Java.Parcelable: A faster and more efficient mechanism, specific to Android. Requires more boilerplate code for implementation.
// Parcelable example
class MyData implements Parcelable {
private int value;
private String text;
// Constructor
public MyData(int value, String text) {
this.value = value;
this.text = text;
}
// Parcelable implementation
protected MyData(Parcel in) {
value = in.readInt();
text = in.readString();
}
public static final Creator<MyData> CREATOR = new Creator<MyData>() {
@Override
public MyData createFromParcel(Parcel in) {
return new MyData(in);
}
@Override
public MyData[] newArray(int size) {
return new MyData[size];
}
};
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(value);
dest.writeString(text);
}
}