Does variable order matter while parcel read/write operation in Parcelable?

笑着哭i 提交于 2019-12-01 03:43:24

问题


I have the following implementation of a Parcelable class:

public class DemoModel implements Parcelable {
    private String para1;
    private int para2;

    public DemoModel(){}

    protected DemoModel(Parcel in) {
        para1 = in.readString();
        para2 = in.readInt();
    }

    @Override
    public void writeToParcel(Parcel parcel, int i) {
        parcel.writeString(para1);
        parcel.writeInt(para2);
    }

    //other methods
}

Is it important to maintain order while write/read to the parcel? And why?


回答1:


Yes it does. Order of write variables is up to you and you can do it as you want, but you must read them in that same exact order. It will give you runtime crash if order will be different.

Why? Mechanism is blind, so it trust you to get it in right order. Mostly for performance benefits, because it don't have to search for a specific element. You can see in Parcelable interface, that it creates array with size of a number of elements you put in parcel.

public interface Creator<T> {
    /**
     * Create a new array of the Parcelable class.
     * 
     * @param size Size of the array.
     * @return Returns an array of the Parcelable class, with every entry
     * initialized to null.
     */
    public T[] newArray(int size);
}



回答2:


According to this source:

One very important thing to pay close attention to is the order that you write and read your values to and from the Parcel. They need to match up in both cases.

It's caused by the way parcelable is implemented by its creators



来源:https://stackoverflow.com/questions/43800772/does-variable-order-matter-while-parcel-read-write-operation-in-parcelable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!