I'm using the Firestore reference data type to store a reference to a User as shown in the screenshots below
User reference
Users collections
When I try to query this data, I get a ClassCastException
(I tried to cast to a String
just for the sake of it).
Code
//.. this function reads data from DocumentSnapshot
//.. and converts to an Organization
private fun DocumentSnapshot.toOrganization(): Organization {
//.. some code
(this.data["members"] as ArrayList<HashMap<String, Any>>).map { toOrgMember(it) })
//.. more code
}
fun toOrgMember(map: Map<String, Any>): OrgMember {
//map["user"] as String throws ClassCastException. Refer first screenshot
return OrgMember(map["id"] as Long, UserRef(map["user"] as String), map["type"] as String,
asJobTitlesList(map["jobTitles"] as String))
}
Stacktrace
10-14 20:31:17.503 15569-15569/com.a.b W/System.err: Caused by: java.lang.ClassCastException: com.google.android.gms.internal.zzegf cannot be cast to java.lang.String
10-14 20:31:17.504 15569-15569/com.a.b W/System.err: at feature.model.core.CoreUtilsKt.toOrgMember(CoreUtils.kt:28)
10-14 20:31:17.504 15569-15569/com.a.b W/System.err: at feature.model.organization.OrgRemoteKt.toOrganization(OrgRemote.kt:55)
To what class should I cast the reference data type? (com.google.android.gms.internal.zzegf
seems like an internal class which shouldn't be used)
As of now, I didn't find any example in the docs for a reference type. Any help would be appreciated.
REFERENCE DATA TYPE IS ONE OF THE MANY DATA TYPES OF CLOUD FIRESTORE . THIS DATA TYPE ACTS LIKE FOREIGNKEY EVEN THOUGH IT IS NOT ACTUALLY A FOREIGNKEY . THE MAIN ADVANTAGE OF USING IT IS TO REFER A CERTAIN DOCUMENT TO ANOTHER DOCUMENT .
There are three ways to retrieve data stored in Cloud Firestore. Any of these methods can be used with documents, collections of documents, or the results of queries: Call a method to get the data once. Set a listener to receive data-change events.
A DocumentReference refers to a document location in a Firestore database and can be used to write, read, or listen to the location. The document at the referenced location may or may not exist. A DocumentReference can also be used to create a CollectionReference to a subcollection.
A Reference represents a specific location in your Database and can be used for reading or writing data to that Database location. You can reference the root or child location in your Database by calling firebase. database(). ref() or firebase.
Firestore returns a DocumentReference when getting a reference from your collections. If changing the cast to DocumentReference doesn't work, keep track of this issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With