简体   繁体   中英

How to get array from Firestore and loop through it in Android?

I am trying to get a field called services which is an array of Strings from the Firestore document.

I am doing it like this:

    fAuth = FirebaseAuth.getInstance();
    fStore = FirebaseFirestore.getInstance();
    
      fAuth.signInWithEmailAndPassword(Etemail.getText().toString(), Etpassword.getText().toString()).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
                    @Override
                    public void onSuccess(AuthResult authResult) {
  
                        Uid = authResult.getUser().getUid();
                        checkUserAccessLevel(Uid);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {

                        Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });
                
                 private void checkUserAccessLevel(String uid) {
                 
                 DocumentReference df = fStore.collection("Users").document(uid);

                df.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            
            if (task.isSuccessful()) {
                List<String> services = new ArrayList<>();
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    Map<String, Object> map = document.getData();
                    for (Map.Entry<String, Object> entry : map.entrySet()) {
                        services.add(entry.getValue().toString());
                    }
                    Log.d(TAG, services.toString());
                    
                } else {
                    Log.d(TAG, "No such document");
                }
            } else {
                Log.d(TAG, "get failed with ", task.getException()); 
            }
        }

    });
                 
}

This is the screenshot of Firebase Firestore DB!

Please help me to achieve the task.

To get the values that exist within your "services" array, you need to read the content of the document. Remember that DocumentSnapshot's getData() method, returns a Map<String, Object> that can be simply iterated, as the following lines of code:

FirebaseFirestore fStore = FirebaseFirestore.getInstance();
DocumentReference df = fStore.collection("Users").document(uid);
df.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        if (task.isSuccessful()) {
            List<String> services = new ArrayList<>();
            DocumentSnapshot document = task.getResult();
            if (document.exists()) {
                Map<String, Object> map = document.getData();
                for (Map.Entry<String, Object> entry : map.entrySet()) {
                    services.add(entry.getValue().toString());
                }
                Log.d(TAG, services.toString());
                //Do what you need to do with your services List
            } else {
                Log.d(TAG, "No such document");
            }
        } else {
            Log.d(TAG, "get failed with ", task.getException()); //Don't ignore potential errors!
        }
    }
});

The result in the logcat will be:

[Cardiology, Oncology, Neurology, Urology]

You can use either get() method or getData() method.

  • get() method takes a String parameter (field name - note the there are also different versions of this method) and returns Object and you need to caste to your data type. You can use it for a single field (or more fields) if you don't want to get whole data from document as a Map<String, Object> .
  • getData() method returns whole data from document as Map<String, Object> . String is the document's fields names and Object is the data belongs to that fields. With your field name (or names) you can get the data belong to that field (or fields). Also you need to cast to your data type.

Get data according to the field name with using get() method:

 df.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        List<String> services = new ArrayList<>(),
                                timeSlot = new ArrayList<>();
                        if (document.exists()) {
                            services = (List<String>) document.get("services");
                            timeSlot = (List<String>) document.get("time_slot");
                        } else {
                            Log.e(TAG, "Document is not exist");
                        }
                    }else{
                        Log.e(TAG, "Task Failed: " + task.getException());
                    }
                }
            });

Get all data with getData() method and get your field values with using fields' names:

df.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                    if (task.isSuccessful()) {
                        DocumentSnapshot document = task.getResult();
                        List<String> services = new ArrayList<>(),
                                timeSlot = new ArrayList<>();
                        if (document.exists()) {
                            Map<String, Object> data = document.getData();
                            services = (List<String>) data.get("services");
                            timeSlot = (List<String>) data.get("time_slot");
                        } else {
                            Log.e(TAG, "Document is not exist");
                        }
                    }else{
                        Log.e(TAG, "Task Failed: " + task.getException());
                    }
                }
            });

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