Conta
Conta

Reputation: 176

Java Android Get the name of a collection from the Firestore Firebase

I'm trying to retrieve the name of the first collection that appears in "userPosts":

enter image description here

I then tried to do this:

FirebaseFirestore.getInstance().collection("post").document(listUserId).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
    @Override
    public void onComplete(@NonNull Task<DocumentSnapshot> task) {
        Toast.makeText(MainActivity.this, "" + task.getResult().getString("userPosts"), Toast.LENGTH_LONG).show();
    }
});

But the result is "null".

Is there a way to get the name of the first collection in userPosts (which is a document)?

Upvotes: 1

Views: 353

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138944

To get the name of the 3f*b...a!jz document, you need to create a reference that points to the userPosts collection and then use a get() call, as you can see in the following lines of code:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference userPostsRef = rootRef.collection("post").document(listUserId).collection("userPosts");
userPostsRef.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());
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

The result in the logcat will be:

3f*b...a!jz

Upvotes: 1

Related Questions