Reputation: 1833
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.
Upvotes: 6
Views: 8891
Reputation: 91
I suffer same your problem. However I can solve this problem using:
DocumentReference docRef = firestore.document(map.get("reference_field").toString());
I'm not sure that this is correct way, but this way works for me.
-- Update --
It seems new firestore version (11.6.0) on android can't use my way. However it can be cast directly
DocumentReference docRef = (DocumentReference) map.get("reference_field");
Upvotes: 1
Reputation: 185
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.
Upvotes: 3
Reputation: 762
We will need to see some of your code to give you an answer. but in the meantime here is what my query snippet looks like, it assumes you are looking for something unique if not you can loop through the results.
FireBaseFirestore db = FirebaseFirestore.getInstance();
collectionRef = db.collection("yourCollection");
Query query = collectionRef.whereEqualTo("Field", "yourQuery" );
query.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()) {
QuerySnapshot qSnap = task.getResult();
if (!qSnap.isEmpty()) {
Log.d("Query Data", String.valueOf(task.getResult().getDocuments().get(0).getData()));
} else {
Log.d("Query Data", "Data is not valid");
}
}
}
});
Upvotes: 2