Write Parcelable for ArrayList<String []> in android?

荒凉一梦 提交于 2019-12-13 07:03:42

问题


I just created model with String array and array list of string array.Like this

public class LookUpModel implements Parcelable
{
    private String [] lookup_header;
    private ArrayList<String []> loookup_values;

 public void writeToParcel(Parcel dest, int flags) {

            dest.writeStringArray(getLookup_header());

        };

}

I have implemented parcelbale then write for String [] but how to do for the ArrayList<String []> and that values need to pass to another activity.Thanks in advance.


回答1:


Use dest.writeStringList(loookup_values); Refer to the following http://developer.android.com/reference/android/os/Parcel.html#writeStringList(java.util.List) Hope that helps.




回答2:


Simplest way I could think about is the following:

public static final class LookUpModel implements Parcelable {
    private String [] lookup_header;
    private ArrayList<String []> lookup_values;

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

    public void writeToParcel(Parcel dest, int flags) {

        dest.writeStringArray(lookup_header);

        dest.writeInt(lookup_values.size());

        for (String[] array : lookup_values) {
            dest.writeStringArray(array);
        }
    };

    public static final Parcelable.Creator<LookUpModel> CREATOR
            = new Parcelable.Creator<LookUpModel>() {
        public LookUpModel createFromParcel(Parcel in) {
            return new LookUpModel(in);
        }

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

    /**
     * Specific constructor for Parcelable support
     * @param in
     */
    private LookUpModel(Parcel in) {
        in.readStringArray(lookup_header);

        final int arraysCount = in.readInt();

        lookup_values = new ArrayList<String[]>(arraysCount);

        for (int i = 0; i < arraysCount; i++) {
            lookup_values.add(in.createStringArray());
        }
    }
}


来源:https://stackoverflow.com/questions/17417623/write-parcelable-for-arrayliststring-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!