保存onSaveInstanceState

时间:2016-06-22 11:24:03

标签: android

我想在屏幕旋转后不重新加载RecyclerView。我发现我需要从List存储/恢复Adapter。不是吗?

但是有问题:

Found java.util.List<Department> requried java.util.ArrayList<?extends android.os.Parcelable>

当我尝试将列表放入捆绑包时:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList("key", mAdapter.getList());
}

mAdapter.getList()从RecyclerView适配器返回List<Department>

但我在Parcelable模型类中实现了Department

@Parcel
public class Department implements UrlInterface,Parcelable {

    @SerializedName("department_id")
    @Expose
    String departmentId;
    @SerializedName("short_name")
    @Expose
    String shortName;
    @Expose
    String url;
    @Expose
    HashMap<Integer, Category> categories;

    public Department() {}

    protected Department(android.os.Parcel in) {
        departmentId = in.readString();
        shortName = in.readString();
        url = in.readString();
    }

    public static final Creator<Department> CREATOR = new Creator<Department>() {
        @Override
        public Department createFromParcel(android.os.Parcel in) {
            return new Department(in);
        }

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

    public String getDepartmentId() { return departmentId; }

    public void setDepartmentId(String departmentId) { this.departmentId = departmentId; }

    public String getShortName() { return shortName; }

    public void setShortName(String shortName) { this.shortName = shortName; }

    @Override
    public String getUrl() { return url; }

    @Override
    public String getFullName() { return shortName; }

    public void setUrl(String url) { this.url = url; }

    public HashMap<Integer, Category> getCategories() { return categories; }

    @Override
    public String toString() { return shortName; }

    @Override
    public String getImageUrl() { return null; }

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

    @Override
    public void writeToParcel(android.os.Parcel dest, int flags) {
        dest.writeString(departmentId);
        dest.writeString(shortName);
        dest.writeString(url);
    }
}

有什么问题?

2 个答案:

答案 0 :(得分:10)

ArrayListList的子类,从List投射到ArrayList ....糟糕的想法......它会产生问题,特别是对于可分配的东西

因此,快速解决方案是:

outState.putParcelableArrayList("key", new ArrayList<Department>(mAdapter.getList()));

答案 1 :(得分:0)

上述解决方案对我不起作用,并继续引发错误。以下解决方案(由Android Studio提供)对我有效-

outState.putParcelableArrayList("message_list", (ArrayList<? extends Parcelable>) messageList);

以防万一其他人也跌倒在该线程中寻找相似的解决方案!