Lionlollipop
Lionlollipop

Reputation: 123

Android: Get field values from sub-collection

Is there a way to get data from sub-collection? Below is the structure of my database, for each user, only one document will be created in the "userinfo" subcollection to store just the username and email.

I am trying to get the "username" and "email" values from Firestore then set the values to strings like:

String username = ? String email = ?

"main"(root_collection)
            |
            |=>userid1(auto-generated)
                         |                  
                         |=>"userinfo"(sub-collection)=>documentID(auto)=>username: mary
                         |                                              =>email:[email protected]
                         |                                             
                         |                            
                         |=>"emotions"(sub-collection)=>documentID(auto)=>happy: true
                                                                        =>sad:false
                                                                        =>depressed:false

I read some other answers from other questions saying that the field value could be retrieved using

String value = documentSnapshot.getString("field");

but I still don't know how to do it? I wrote a little something and I don't know how to get the value.

 FirebaseAuth mAuth = FirebaseAuth.getInstance();
        String userId = Objects.requireNonNull(mAuth.getCurrentUser()).getUid();

        FirebaseFirestore db = FirebaseFirestore.getInstance();
        CollectionReference userRef = db.collection("main").document(userId).collection("userinfo");

        userRef.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                //get the value
                String value = queryDocumentSnapshots.getDocuments("username"); // how ??
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(SettingsActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
            }
        });

also have an object class UserInfo

import java.io.Serializable;

public class UserInfo implements Serializable {

    private String email, username;

    public UserInfo() {}

    public UserInfo(String email, String username) {
        this.email = email;
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Please help, thanks so much.

Upvotes: 0

Views: 51

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138869

Is there a way to get data from sub-collection?

Yes, there is. To get that data, you have to loop through the result as in the following lines of code:

userRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                String value = document.getString("username");
                Log.d("TAG", value);
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

The result in the logcat will be:

mary

Upvotes: 2

Related Questions