将自定义对象列表作为另一个活动的意图发送

时间:2014-07-04 15:25:15

标签: android android-intent parcelable

我有一个类Tag模型,我需要发送List< TagModel>到另一个活动。 如果我实现parcelable,那么我的项目中有另一个自定义对象数组列表。 如何解决这个问题?

public class TagModel {

    int listing_count;
    ArrayList<ListingsModel> listingsModel;  //how to handle this list
    String foodTypeName;

    public int getListing_count() {
        return listing_count;
    }

    public void setListing_count(int listing_count) {
        this.listing_count = listing_count;
    }

    public String getFoodTypeName() {
        return foodTypeName;
    }

    public void setFoodTypeName(String foodTypeName) {
        this.foodTypeName = foodTypeName;
    }

    public ArrayList<ListingsModel> getListings() {
        return listingsModel;
    }

    public void setListings(ArrayList<ListingsModel> listingsModel) {
        this.listingsModel = listingsModel;

    }
}

1 个答案:

答案 0 :(得分:3)

您必须有两个对象可以发送。

我假设你的对象&#34; ListingsModel&#34;已经是好事了。

TagModel Parceable

public class TagModel implements Parcelable {

int listing_count;
ArrayList<ListingsModel> listingsModel;  //how to handle this list
String foodTypeName;

public int getListing_count() {
    return listing_count;
}

public void setListing_count(int listing_count) {
    this.listing_count = listing_count;
}

public String getFoodTypeName() {
    return foodTypeName;
}

public void setFoodTypeName(String foodTypeName) {
    this.foodTypeName = foodTypeName;
}

public ArrayList<ListingsModel> getListings() {
    return listingsModel;
}

public void setListings(ArrayList<ListingsModel> listingsModel) {
    this.listingsModel = listingsModel;

}

protected TagModel(Parcel in) {
    listing_count = in.readInt();
    if (in.readByte() == 0x01) {
        listingsModel = new ArrayList<ListingsModel>();
        in.readList(listingsModel, ListingsModel.class.getClassLoader());
    } else {
        listingsModel = null;
    }
    foodTypeName = in.readString();
}

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(listing_count);
    if (listingsModel == null) {
        dest.writeByte((byte) (0x00));
    } else {
        dest.writeByte((byte) (0x01));
        dest.writeList(listingsModel);
    }
    dest.writeString(foodTypeName);
}

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

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

对于parcelable对象,我建议使用这个伟大的工具parcelabler