Reputation: 46
/Info/Semestre1/Courses/course1 Is my full data base reference. I'm trying to access all the courses name of all the semesters at ounce.
db.collection("Courses").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
}
// Log.d(TAG, document.getId() + " => " + document.getData());
}
}
});
}
I
I got all the semesters of Info. Now how can I access all the courses names?
Upvotes: 2
Views: 1237
Reputation: 1420
You are doing the same mistake which i done when i was learning more about firestore.
So the first mistake you are doing is directly accessing the "Courses" collection which
is not possible if you want to access the "Courses" collection then you must need to traverse through all the collection and document before it.
Ex :collection1/doc1/collection2/doc2/collection3
Now if you want to access the data of the collection3 then query for that is going to be like
collection1.doc().collection2.doc2().collection3.get() and then your listner thats just basic understanding before we move for you answer.
Now ans of you question
db.collection("info").document("sem-id").collection(Courses).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
}
// Log.d(TAG, document.getId() + " => " + document.getData());
}
}
});
}
Let me know if still any doubt.Happy coding
Upvotes: 3
Reputation: 317928
I think your query in the question is actually incorrect. Based on what I see in your screenshot, to get all the semesters, you would do this:
db.collection("Info").get()
Then, to get all the courses for a specific semester in the subcollection nested under the semester, you would need a whole new query like this:
String courseId = ... // changes as you iterate the courses in Info
db.collection("Info").document(courseId).collection("Courses").get()
You can't get all the semesters and courses in one query with the database structure you have now. Firestore queries are shallow, meaning they don't consider subcollections at all. Each subcollection requires its own separate query.
Upvotes: 2