0

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 :)

Alberto Garrido
  • 485
  • 2
  • 6
  • 15
  • 2
    You never instantiate the List to create an instance. You need `private ArrayList categoryIds = new ArrayList()`; The `new ArrayList()` is the crucial part, as this is where you construct the object instance. – TEK Aug 28 '15 at 15:24
  • It's the first time I use an ArrayList in a parcel. So far I have also my custom class' array: ArrayList and no need to instantiate. But you're completely right, it worked, thanks!! if you post it as an answer I will accept it. – Alberto Garrido Aug 28 '15 at 15:31
  • Done. Glad I could help in some fashion. :) – TEK Aug 28 '15 at 15:33

2 Answers2

0

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.

Community
  • 1
  • 1
TEK
  • 1,265
  • 1
  • 15
  • 30
0

Use below code to read lists:

categoryIds = in.createStringArrayList()
Abdullah
  • 7,143
  • 6
  • 25
  • 41