gpt4 book ai didi

android - 通过 Intent 传递和 ArrayList

转载 作者:搜寻专家 更新时间:2023-11-01 08:30:54 25 4
gpt4 key购买 nike

我有一个名为 Service 的类,它用于使用此构造函数创建 Service 对象

public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}

然后我用下面的签名创建一个列表调用服务列表

List<Service> serviceList = new ArrayList<Service>

我尝试像这样通过 Intent 对象传递这个 ArrayList

Intent i = new Intent(Classname.this, anotherClass.class);
i.putExtras("serviceList",serviceList);
startActivity(i);

但是失败了。我使用 ArrayList 对象传递 Intent 的方式是什么。

最佳答案

您的自定义类必须实现 ParcelableSerializable为了在 Intent 中序列化/反序列化。

你的类(class) Service例如必须看起来像这样(使用生成器 http://www.parcelabler.com/ )

public class Service implements Parcelable {
private int id;
private String service_name;
private String service_code;
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}


protected Service(Parcel in) {
id = in.readInt();
service_name = in.readString();
service_code = in.readString();
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(service_name);
dest.writeString(service_code);
}

@SuppressWarnings("unused")
public static final Parcelable.Creator<Service> CREATOR = new Parcelable.Creator<Service>() {
@Override
public Service createFromParcel(Parcel in) {
return new Service(in);
}

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

然后你可以使用getIntent().getParcelableArrayListExtra()类型转换

ArrayList<Service> serviceList= intent.<Service>getParcelableArrayList("list"));

发送给你这样用

intent.putParcelableArrayListExtra("list", yourServiceArrayList);

请注意 yourServiceArrayList应该是一个 ArrayList

如果是List则可以通过

intent.putParcelableArrayListExtra("list", (ArrayList<? extends Parcelable>) yourServiceArrayList);

关于android - 通过 Intent 传递和 ArrayList<Service>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41014704/

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