What is the difference between Serializable and Parcelable ? Which is best approach in Android?
Copied from Link
Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.
Parcelable is an Android specific interface where you implement the serialization yourself. if a class implements Parcelable interface, then the instances of this class can be written to and restored from a Parcel.
用例:使用Bundle在设备旋转时保存 Parcelable 数据,prevent custom views from losing state across screen orientation changes。
public class Box implements Parcelable {
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeValue(mOrigin);
out.writeValue(mCurrent);
}
public static final Parcelable.Creator<Box> CREATOR = new Parcelable.Creator<Box>() {
@Override
public Box createFromParcel(Parcel in) {
return new Box(in);
}
@Override
public Box[] newArray(int size) {
return new Box[size];
}
};
private Box(Parcel in) {
mOrigin = (PointF) in.readValue(null);
mCurrent = (PointF) in.readValue(null);
}
}
public class BoxDrawingView extends View {
private static final String PARCEL_KEY_STATE = "instanceState";
private static final String PARCEL_KEY_BOXES = "boxes";
@Override
protected Parcelable onSaveInstanceState() {
super.onSaveInstanceState();
Bundle bundle = new Bundle();
bundle.putParcelable(PARCEL_KEY_STATE, super.onSaveInstanceState());
bundle.putParcelableArrayList(PARCEL_KEY_BOXES, mBoxes);
return bundle;
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
if (state instanceof Bundle) {
Bundle bundle = (Bundle)state;
mBoxes = bundle.getParcelableArrayList(PARCEL_KEY_BOXES);
// 如果没有下面这行代码,将导致 IllegalArgumentException.
// RuntimeException: Unable to start activity ComponentInfo{.DragAndDraw}:
// java.lang.IllegalArgumentException: Wrong state class, expecting View State but received class Bundle instead.
// This usually happens when two views of different type have the same id in the same hierarchy.
state = bundle.getParcelable(PARCEL_KEY_STATE);
}
super.onRestoreInstanceState(state);
}
}