Parcelable serialized objects in Android

  • 2020-12-26 05:53:09
  • OfStack

Today I looked up the Parcelable interface, which is the serialized object interface provided by android, compared to java
Serializable is more efficient. There are two main steps to serializing an object through this interface:
1. Implement public void writeToParcel(Parcel dest, int flags) {};
2. Instantiate CREATOR


	public static final Parcelable.Creator<ParcelableImpl> CREATOR = new Parcelable.Creator<ParcelableImpl>() {

		@Override
		public ParcelableImpl createFromParcel(Parcel source) {

			return new ParcelableImpl(source);
		}

		@Override
		public ParcelableImpl[] newArray(int size) {

			return new ParcelableImpl[size];
		}
	};

Please refer to the following code for details:


import android.os.Parcel;
import android.os.Parcelable;

public class ParcelableImpl implements Parcelable {

	private int num;

	ParcelableImpl(Parcel in) {
		num = in.readInt();
	}

	@Override
	public int describeContents() {
		return 0;
	}

	// will ParcelableImpl Object serialized as 1 a Parcel object 
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		dest.writeInt(num);
	}

	// CREATOR  It has to be capitalized, and it has to be" CREATOR " 
	public static final Parcelable.Creator<ParcelableImpl> CREATOR = new Parcelable.Creator<ParcelableImpl>() {

		// will Parcel Object is serialized to ParcelableImpl
		@Override
		public ParcelableImpl createFromParcel(Parcel source) {
			return new ParcelableImpl(source);
		}

		@Override
		public ParcelableImpl[] newArray(int size) {
			return new ParcelableImpl[size];
		}
	};
}

Related articles: