Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Firebase toObject with ref

With cloud firestore, you can convert a document to your object with document.toObject(YourClass.class); where the class's variables match those in your database. However, if one of the variables in the database is a reference, which data type would you use in the java class? Note that I need to not only store it in my data model but retrieve it and set it with the override methods of the form:

protected MyDataModel(Parcel in) {
    mString = in.readString();
}

and

@Override
public void writeToParcel(Parcel parcel, int i) {
    parcel.writeString(mString);
}

If I use a DocumentReference, then in writeToParcel(), how would I write it? Also, how would I read it in the protected Parcel in constructor? I have tried writeSerializable() and readSerializable() but DocumentReference does not implement Serializable.

like image 530
Paradox Avatar asked Mar 29 '26 00:03

Paradox


2 Answers

I haven't used the Java API yet but I imagine you'll want to use the DocumentReference type. Here are some links in the firebase documentation:
DocumentReference
CollectionReference
getDocumentReference

like image 154
ackushiw Avatar answered Apr 02 '26 07:04

ackushiw


If you need to serialize a DocumentReference, 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, use FirebaseFirestore.getInstance().document(path).

When you have conversions like this to make, sometimes it more convenient to write all the code yourself rather than using the built-in object serialization provided by the Firestore SDK.

like image 45
Doug Stevenson Avatar answered Apr 02 '26 07:04

Doug Stevenson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!