Search code examples
androidarraylistparcelableparcel

ArrayList<String> null when building Parcel


One of my classes has 3 properties ArrayList like this:

public class Product implements Parcelable{

// other properties

private ArrayList<String> categoryIds;
private ArrayList<String> categorySlugs;
private ArrayList<String> categoryNames;

public Product(){}

// getters and setters

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

@Override
public void writeToParcel(Parcel dest, int flags) {
    // writing other properties
    dest.writeStringList(categoryIds); // here aren't null
    dest.writeStringList(categorySlugs);
    dest.writeStringList(categoryNames);
}

public static final Parcelable.Creator<Product> CREATOR = new Parcelable.Creator<Product>() {
    public Product createFromParcel(Parcel pc) {
        return new Product(pc);
    }
    public Product[] newArray(int size) {
        return new Product[size];
    }
};

public Product(Parcel in){

    // reading other properties, all correct

    in.readStringList(categoryIds); // from here are all null
    in.readStringList(categorySlugs);
    in.readStringList(categoryNames);
}

}

Read the comments in the Parcel constructor. Those three are null but in the function "writeToParcel" they are not null. All other properties are correct. What I'm missing here?

Thanks :)


Solution

  • You never instantiate the List to create an instance.

    For example, you need:

    private ArrayList<String> categoryIds = new ArrayList<String>();

    The new ArrayList<String>() is the crucial part, as this is where you construct the object instance.

    Better yet, construct these Lists in the constructor of Product. Also consider coding to interface, too.