Search code examples
javaandroidarraylistparcelable

Read and write Parcel when using ArrayList of ArrayList


I'm trying to read and write this ArrayList structured as well: ArrayList<ArrayList<Pair<Float,Float>>> points I've seen that the only way would by using the class inside the external ArrayList, but in this case I haven't it. This is my full class, how do I can implement it?

import android.os.Parcel;
import android.os.Parcelable;
import android.util.Pair;
import java.io.Serializable;
import java.util.ArrayList;

public class Cornice implements Serializable, Parcelable {

    private String number;
    private ArrayList<ArrayList<Pair<Float,Float>>> points;

    public Cornice(String n, ArrayList<ArrayList<Pair<Float,Float>>> p) {
        number = n;
        if (p!=null) points = new ArrayList<>(p);
        else points=new ArrayList<>();
    }

    protected Cornice(Parcel in) {
        number = in.readString();
        points = //MISSING
    }

    public String getNumber () {
        return number;
    }

    public ArrayList<ArrayList<Pair<Float,Float>>> getPoints () {
        return points;
    }

    public static final Creator<Cornice> CREATOR = new Creator<Cornice>() {
        @Override
        public Cornice createFromParcel(Parcel in) {
            return new Cornice(in);
        }

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

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

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(number);
        //MISSING
    }
}

Solution

  • Pair is neither Parcelable, nor Serializable, so what you are trying to do won't work. You will have to change the data structure you use to hold the points to something else. For example you can convert it something like this:

    private ArrayList<ArrayList<Float[]>> points;
    

    or even (if you do not want to support null values) to:

    private ArrayList<ArrayList<float[]>> points;