gpt4 book ai didi

android - 在 onSaveInstanceState 中保存对象列表

转载 作者:太空宇宙 更新时间:2023-11-03 11:47:43 25 4
gpt4 key购买 nike

我不想重新加载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()返回 List<Department>来自 RecyclerView 的适配器。

但我已经实现了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);
}
}

怎么了?

最佳答案

ArrayListList 的子类, 从 List 类型转换至 ArrayList ....坏主意...它会产生问题,尤其是对于可打包的东西。

所以快速的解决方案是:

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

关于android - 在 onSaveInstanceState 中保存对象列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37966608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com