The Parcelable package error occurs when data is transmitted through the parcelable protocol.
The Parcelable method used to pass custom object data to Intent for the first time recently. Let's talk about the implementation method of Parcelable.
The implementation principle of Parcelable is to first decompose a complete object. Each part after the decomposition is a type supported by Intent, so that the object passing function is realized.
Parcelable needs to implement three things:
1) describeContents method. This method returns 0 directly;
2) writeToParcel method. This method calls the writeXXX () method of Parcel to write the data of the class to the external provided Parcel;
3) provide a static CREATOR constant to implement Parcelable. creator interface. This interface needs to override two methods. newArray (int size) only needs to generate an array of the custom object, you can use the size passed in the method to return the array size. in the createFromParcel (Parcel in) method, we need to implement the function of writing data from in;
Android sample code:
/*** Media entity class */public class Media implements Parcelable {private String name; private String uri; private String singer; private String id; private int duration; private int album_id; private String key; public Media (){}...... ...... @ Override public void writeToParcel (Parcel dest, int flags) {dest. writeString (name); dest. writeString (uri); dest. writeString (singer); dest. writeString (id); dest. writeInt (duration); dest. writeInt (album_id); dest. writeString (key);} public static final Parcelable. creator <Media> CREATOR = new Creator <Media> () {@ Override public Media [] newArray (int size) {return new Media [size];} @ Override public Media createFromParcel (Parcel in) {return new Media (in) ;}; public Media (Parcel in) {name = in. readString (); uri = in. readString (); singer = in. readString (); id = in. readString (); duration = in. readInt (); album_id = in. readInt (); key = in. readString ();}}
In the actual development process, the system reports java when obtaining data. lang. runtimeException: Parcel android. OS. parcel @ 4aa21e7c.
Later, I read it carefully and found that during development, I called public Media (Parcel in) in public Media createFromParcel (Parcel in) to retrieve data and set duration = in. readInt () and album_id = in. if the order of readInt (); is reversed, it will be correct. The root cause is that the order must be the same for splitting and retrieving. Remember!