Reputation: 1926
I have a firestore database document that essentially looks like this:
{
"name": "George",
"weeks": [
{
"checked": true,
"days": [
{
"checked": true,
"exercises": [
{
"exercise": "Bench Press",
"sets": [
{
"weight": 300,
"reps": 20
},
{
"weight": 400,
"reps": 30
}
]
}
]
}
]
}
]
}
I know I can get the data for the document by doing:
FirebaseFirestore db = FirebaseFirestore.getInstance();
CollectionReference userRef = db.collection("users");
Query usersDataQuery = userRef.whereEqualTo("name", "George");
usersDataQuery.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()){
for(QueryDocumentSnapshot document: task.getResult()){
Log.d("data = ", document.getId() + " => " + document.getData());
}
}
}
});
but then document .getData() comes back as:
2 => {weeks=[{days=[{exercises=[{sets=[{weight=300, reps=20}, {weight=400, reps=30}, {weight=500, reps=40}], exercise=Bench Press}, {sets=[{weight=300, reps=20}, {weight=400, reps=30}, {weight=500, reps=40}], exercise=Skull Crushers}, {sets=[{weight=300, reps=20}, {weight=400, reps=30}, {weight=500, reps=40}], exercise=Flyes}, {sets=[{weight=600, reps=20}, {weight=900, reps=30}, {weight=780, reps=40}], exercise=Incline Bench Press}], checked=true}], checked=true}], name=George}
And I have no way of getting to the weight in the first index of "sets". You would think you could do something like:
document.getData()["weeks"][0]["days"][0]["exercises"][0]["sets"][0]["weight"]
But I have not found a way to do it like this. Let me know if there is a good solution to getting data like that.
Upvotes: 1
Views: 957
Reputation: 317467
As you can see from the API documentation, getData() returns a Map of all the fields and their values in the document. You need to dive into these values.
Also note that each field value in a document will surface as an appropriate Java type that describes each value. So, if a field contains an object, the field value type will be a Map<String,Object>
whose keys and values are going to be the properties and values of that object. If a field value contains an array, You'll get a List<Object>
that contains each value of the array.
Since you have a lot of nested lists and object, you will end up writing a lot of code that unpacks each of these lists and maps to discover your data. You might end up doing a lot of debug logging to learn how to do this effectively.
Upvotes: 1