传递和 ArrayList<Service>通过意图 [英] Passing and ArrayList<Service> through intent
问题描述
我有一个叫做Service的类,它用来使用这个构造函数来创建Service对象
I have a class called Service, which is used to create Service objects using this constructor
public Service(int id, String service_name, String service_code) {
this.id = id;
this.service_name = service_name;
this.service_code = service_code;
}
然后我创建一个列表调用服务列表,如下签名
then I create a list call service list as with the following signature
List<Service> serviceList = new ArrayList<Service>
我尝试通过这样的Intent
对象传递这个ArrayList
I have try to pass this ArrayList through Intent
Object like this
Intent i = new Intent(Classname.this, anotherClass.class);
i.putExtras("serviceList",serviceList);
startActivity(i);
但它失败了.我通过 ArrayList 对象传递意图的方式是什么.
But it fails. What is the way I pass through intent with ArrayList object.
推荐答案
您的自定义类必须实现 Parcelable
或 Serializable
以便在一个意图.
Your custom class has to implement Parcelable
or Serializable
in order to serialize/de-serialize within an Intent.
你的类 Service
必须看起来像这样(使用生成器 http://www.parcelabler.com/)
Your class Service
has to look like this for example (used a generator 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()
进行转换
Then you can use getIntent().getParcelableArrayListExtra()
with casting
ArrayList<Service> serviceList= intent.<Service>getParcelableArrayList("list"));
发送给你这样使用
intent.putParcelableArrayListExtra("list", yourServiceArrayList);
注意 yourServiceArrayList
应该是一个 ArrayList
Note that the yourServiceArrayList
should be an ArrayList
如果是List则可以通过
if it is List the you can pass through
intent.putParcelableArrayListExtra("list", (ArrayList extends Parcelable>) yourServiceArrayList);
这篇关于传递和 ArrayList<Service>通过意图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!