Eloise85
Eloise85

Reputation: 676

Firebase "Parcelable encountered IOException writing serializable object" with object containing ArrayList of DocumentReference

I'm trying to pass to another activity a User object containing an Arraylist of Firestore DocumentReference and when I start the activity I got this exception. I'm not using Parceleable so can you confirm that this error is due to the complexity of the object to pass and I must absolutely use the Parcels instead of simple Serializeable?

Thanks for your help

Upvotes: 4

Views: 696

Answers (2)

Rami Alloush
Rami Alloush

Reputation: 2626

The accepted answer solved the problem for me. I just want to share my implementation for couple of methods to handle the Parcel on the fly! and still have the array as ArrayList<DocumentReference>.

private ArrayList<String> docRefToString(ArrayList<DocumentReference> products) {
    ArrayList<String> newProducts = new ArrayList<String>();
    for (DocumentReference product : products) {
        newProducts.add(product.getPath());
    }
    return newProducts;
}

private ArrayList<DocumentReference> docStringToDoc(ArrayList<String> products) {
    ArrayList<DocumentReference> newProducts = new ArrayList<DocumentReference>();
    for (String product : products) {
        newProducts.add(FirebaseFirestore.getInstance().document(product));
    }
    return newProducts;
}

And in the Parcel implementation ..

private Request(Parcel in) {
    ...
    ArrayList<String> strProducts = in.createStringArrayList();
    this.products = docStringToDoc(strProducts);
    ...
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    ...
    dest.writeStringList(docRefToString(this.products));
    ...
}

Upvotes: 0

Alex Mamo
Alex Mamo

Reputation: 138924

You get that error because DocumentReference class does not implement Parceleable nor Serializable.

If you need to serialize a DocumentReference object you need to use its getPath() method to get a String that describes the document's location in the database. To deserialize that path String back into a DocumentReference object, use the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
DocumentReference ref = rootRef.document(path);

Please see official documentation for FirebaseFirestore.getInstance().document(path) method.

Upvotes: 3

Related Questions