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

馋奶兔 提交于 2020-07-08 11:45:53

问题


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


回答1:


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.




回答2:


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));
    ...
}


来源:https://stackoverflow.com/questions/51305443/firebase-parcelable-encountered-ioexception-writing-serializable-object-with-o

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