使用Parcelable将列表<object>保存到实例状态

时间:2017-06-04 11:28:35

标签: android arraylist android-recyclerview android-savedstate

我有以下型号:

GitItem:

    public class GitItem implements Serializable, Parcelable {
        public int id;
        public String name;
        public String full_name;
        public GitOwner owner;

        public GitItem() {
        }

        public GitItem(Parcel in) {
            id = in.readInt();
            name = in.readString();
            full_name = in.readString();
        }

        public int describeContents() {
            return 0;
        }

        public void writeToParcel(Parcel out, int flags){
            out.writeInt(id);
            out.writeString(name);
            out.writeString(full_name);
        }

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

            @Override
            public GitItem createFromParcel(Parcel source) {
                return new GitItem(source);
            }

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

和GitOwner:

public class GitOwner implements Serializable, Parcelable {
    public String avatar_url;

    public GitOwner(Parcel in) {
        avatar_url = in.readString();
    }

    public GitOwner() {
    }

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {

    }

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

        @Override
        public GitOwner createFromParcel(Parcel source) {
            return  new GitOwner(source);
        }

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

然后在 MainActivity.java 中,我有List<GitItem> data;绑定到RecyclerView

基本上我想要实现的是在我更改List<GitItem>或只是旋转设备时存储Activity的当前状态。不幸的是,即使我已经实现了Parcelable(正如其他帖子所建议的那样),我也无法存储该实例。

对此事的任何帮助都将受到高度赞赏。

1 个答案:

答案 0 :(得分:2)

您尚未在ParcelablewriteToParcel

中实施完整的GitOwner函数,即GitItem

GitOwner班级

@Override
public void writeToParcel(Parcel dest, int flags) {
     dest.writeString(avatar_url);
     // add this line
}

并在GitItem内使用writeParcelable来编写readParcelable来阅读GitItem对象,否则将无法保留和恢复

    public GitItem(Parcel in) {
        id = in.readInt();
        name = in.readString();
        full_name = in.readString();
        owner = in.readParcelable(GitItem.class.getClassLoader());
        // Add line to read owner object
    }

    public void writeToParcel(Parcel out, int flags){
        out.writeInt(id);
        out.writeString(name);
        out.writeString(full_name);
        out.writeParcelable(owner , flags);           
        // Add line to write owner object
    }