Android Parcelable创建数组

时间:2012-12-17 05:02:00

标签: android parcelable

在后台我解析JSON,然后在这个背景中我将Json发送给parcelable 在Parcelable i writestringJSONObject.optString如何编写ArrayList?

List<Row> result = new ArrayList<Row>(array.length());
                for (int i = 0; i < array.length(); i++) {
                    result.add(new Row(array.optJSONObject(i)));
                }

Parcelable.java

public Row(JSONObject from) {
        thumb = from.optString(TAG_THUMBNAILS);
        bigImage = from.optString(TAG_BIG_IMAGE);
        author = from.optString(TAG_AUTHOR);
        description = from.optString(TAG_DESCRIPTION);
        date = from.optString(TAG_DATE);
    }

    public Row(Parcel parcel) {
        thumb = parcel.readString();
        bigImage = parcel.readString();
        author = parcel.readString();
        description = parcel.readString();
        date = parcel.readString();
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(thumb);
        parcel.writeString(bigImage);
        parcel.writeString(author);
        parcel.writeString(description);
        parcel.writeString(date);
    }

1 个答案:

答案 0 :(得分:1)

这不完整但我认为你会明白这一点。会尽力帮助你。

public class Row implements Parceleable{

    private String thumb;
    private String bigImage;
   private String author;
    private String description;
    private String date;

// your setters and getters here
    public void setThumb(String thumb){
        this.thumb = thumb;
    }
    public String getThumb(){
        return thumb;
    }
// ....

    public Row(){
     } 

    public Row(Parcel parcel) {
        thumb = parcel.readString();
        bigImage = parcel.readString();
        author = parcel.readString();
        description = parcel.readString();
        date = parcel.readString();
    }

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

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeString(thumb);
        parcel.writeString(bigImage);
        parcel.writeString(author);
        parcel.writeString(description);
        parcel.writeString(date);
    }

     public static final Parcelable.Creator<Row> CREATOR = new Parcelable.Creator<MyParcelable>() {

    @Override
    public Row createFromParcel(Parcel in) {
        return new Row(in);
    }

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

从你的json填充:

List<Row> myRowArray = new ArrayList<Row>;

Row result;
           for (int i = 0; i < array.length(); i++) {
                result = new Row();
                result.setThumb( fromJson ); //Set thumb string you got from json
                result.setAuthor( fromJson ); //Set Author string you got from json
                 .....
                 myRowArray.add(result);
            }

这就是我们这样做的方式。这很容易。一开始它很容易混淆,但如果你了解这一点,你会发现它很简单,非常方便。