I have a Firestore database looking like this
Where every document has the same fields just with different values. How can I get only one field from every document? For example: Document 1 has kcal with a value of 424 and Document 2 has kcal of value 251 How can I get only that value and not the others? I looked through the internet, Stackoverflow Git, and some other QNA sites, even firebase documentation but can't find what I need.
CodePudding user response:
All Firestore listeners fire on the document level. This means that there is no way you can only get the value of a single field in a document. It's the entire document or nothing. That's the way Firestore works. However, you can only read the value of a single property that exists within multiple documents. To achieve that, please use the following lines of code:
FirebaseFirestore db = FirebaseFirestore.getInstance();
db.collection("Food List").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
if (document != null) {
long kcal = document.getLong("kcal");
Log.d(TAG, "kcal: " kcal);
}
}
} else {
Log.d(TAG, task.getException().getMessage());
}
}
});
The result in the logcat will be:
kcal: 424
.........