在onSaveInstanceState中存储ArrayList

时间:2014-04-04 21:40:06

标签: android mobile android-listview

我在Fragment类中运行一个asynctask并用结果填充ListView。但是,我只在第一次实例化此片段时才运行此asynctask。

如何将ArrayList中asynctask中创建的对象的onSavedInstance存储在putParcelableArrayList中,以便稍后检索它们?

我尝试使用NullPointerException,但在尝试检索时仍然会收到 public class Stops implements Parcelable{ private String station_name; private ArrayList<Stops> stopTitles; public Stops() { } public Stops(Parcel source) { station_name = source.readString(); source.readTypedList(stopTitles, Stops.CREATOR); } public String getStation_name() { return station_name; } public void setStation_name(String station_name) { this.station_name = station_name; } public void setStopTitles(ArrayList<Stops> stopTitles) { this.stopTitles = stopTitles; } public ArrayList<Stops> getStopTitles() { return stopTitles; } @Override public String toString() { return station_name; } @Override public int describeContents() { // TODO Auto-generated method stub return 0; } @Override public void writeToParcel(Parcel dest, int arg1) { // TODO Auto-generated method stub dest.writeString(station_name); dest.writeList(stopTitles); } public static final Parcelable.Creator<Stops> CREATOR = new Parcelable.Creator<Stops>() { @Override public Stops createFromParcel(Parcel in) { return new Stops(in); } @Override public Stops[] newArray(int size) { return new Stops[size]; } };

感谢您的帮助

停止:

{{1}}

}

1 个答案:

答案 0 :(得分:0)

您是否在ArrayList中创建了对象的Parcelable实现?如果对象不可分区,则无法将列表传递给onSavedInstance示例代码:

        public class ParcelableObject implements Parcelable {
        String field;
            @Override
            public int describeContents() {
                return 0;
            }

            @Override
            public void writeToParcel(Parcel dest, int flags) {
                dest.writeValue(field);         
            }

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

                public ParcelableObject createFromParcel(Parcel in) {
                    ParcelableObject obj = new ParcelableObject();
                    obj.readFromParcel(in)
                    return obj;
                }

                public ParcelableObject[] newArray(int size) {
                     return new ParcelableObject[size];
                }
           };

        private void readFromParcel(Parcel in) {
               field = in.readString()
        }
}