我试图通过意图将类型MyCustomObject
的对象发送到另一个活动。我知道,要使类Parcelable,我应该public class MyCustomObject implements Parcelable
,但我不确定自定义对象数组如何在parcelable中工作。这是我到目前为止所得到的..另外,我是否需要使Search类也实现Parcelable?
这是我更新的答案我现在在intent.getParcelableExtra(search)
时获得了一个空对象。也许我没有正确创建搜索数组?
public class MyCustomObject implements Parcelable{
public Search search[];
public MyCustomObject(Parcel in){
in.readArray(MyCustomObject.class.getClassLoader());
}
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags){
dest.writeArray(search)
}
public static final Parcelable.Creator<MyCustomObject> CREATOR = new Parcelable.Creator<MyCustomObject>(){
@Override
public MyCustomObject createFromParcel(Parcel source){
return new MyCustomObject(source);
}
@Override
public MyCustomObject[] newArray(int size){
return new MyCustomObject[size];
}
}
public static class Search implements Parcelable{
public int rank;
public String title;
public String[] imageURL;
public Search(Parcel in){
rank = in.readInt();
title = in.readString();
String[] url = new String[4];
in.readStringArray(url);
url = imageURL
}
@Override
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags){
dest.writeInt(rank);
dest.writeString(title);
dest.writeStringArray(imageURL);
}
public static final Parcelable.Creator<Search> CREATOR = new Parcelable.Creator<Search>(){
@Override
public Search createFromParcel(Parcel source){
return new Search(source);
}
@Override
public Search[] newArray(int size){
return new Search[size];
}
}
}
}
答案 0 :(得分:7)
有几件事。首先,您的Search对象也需要实现Parcelable。接下来,您需要创建一个名为CREATOR的静态字段,该字段实现Parcelable.Creator&lt; MyCustomObject&gt;。这将有一个名为createFromParcel的方法,它返回一个MyCustomObject实例。在这里,您可以从包中读取数据并创建MyCustomObject的新实例。这与writeToParcel基本相反。这一切都适用于搜索,因为你必须使它实现Parcelable。总结:
答案 1 :(得分:1)
当您从Parcel中读取阵列时,您想要读取Search []数组。不是MyCustomObject。
public MyCustomObject(Parcel in){
in.readArray(MyCustomObject.class.getClassLoader());
}