简体   繁体   中英

How can I get same field from different document in FIrestore in Android java

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.

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
.........

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM