简体   繁体   中英

Getting all documents from one collection in cloud Firestore?

I'm starting to learn Android and try to solve this problem for hours. Maybe someone will explain to me how to get all documents from collection -> document from Firestore?

package com.aak.daywork.Activities.ui.home;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aak.daywork.Adapters.PostAdapter;
import com.aak.daywork.Models.Post;
import com.aak.daywork.R;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.firestore.DocumentReference;
import com.google.firebase.firestore.DocumentSnapshot;
import com.google.firebase.firestore.FirebaseFirestore;


import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    RecyclerView postRecyclerView;
    PostAdapter postAdapter;
    FirebaseFirestore firestore;
    DocumentReference documentReference;

    FirebaseAuth mAuth;
    FirebaseUser currentUser;

    List<Post> postList;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        String id = currentUser.getUid();

        documentReference = firestore.collection("Post").document(id);
         //Я пытался это
       // Я получаю только через id

        return root;
    }
    @Override
    public void onStart(){
        super.onStart();
        documentReference.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
            @Override
            public void onSuccess(DocumentSnapshot documentSnapshot) {
                postList = new ArrayList<>();
                Post post = documentSnapshot.toObject(Post.class);
                postList.add(post);
                postAdapter = new PostAdapter(getActivity(), postList);
                postRecyclerView.setAdapter(postAdapter);
            }
        });
    }
}

Often, it is very useful to read the official documentation, in which everything is well-written.

firestore.collection("Post")
    .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() + " => " + document.getData());
                }
            } else {
                Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }
    });

This code was advised to me. I did not understand how to embed it in my code.

enter image description here

Use addSnapshotListener() method to get all the documents in one collection

firestore.collection("Post")
         .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                    if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {
                        
                        List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                        for (DocumentSnapshot value : documents) {
                            
                            Map<String, Object> mapInfo = value.getData();
                            if (mapInfo != null) {

                                String path = value.getReference().getPath();
                                switch (path) {

                                    case "Post" + "/" + "2E3eQpxe....9Y12":
                                        JSONObject info1 = new JSONObject(mapInfo);
                                        info1.optString("city", "");
                                        info1.optString("date", "");
                                        break;

                                    case "Post" + "/" + "D7RP0KLv....fwCh2":
                                        JSONObject info2 = new JSONObject(mapInfo);
                                        info2.optString("city", "");
                                        break;
                                }
                            }
                        }
                    }
                }
            });

CODE:

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private RecyclerView postRecyclerView;
    private PostAdapter postAdapter;
    private FirebaseFirestore firestore;
    private DocumentReference documentReference;

    private FirebaseAuth mAuth;
    private FirebaseUser currentUser;

    private List<Post> postList;
    private String userId;

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        return root;
    }

    @Override
    public void onStart(){
        super.onStart();

        homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
        postRecyclerView = root.findViewById(R.id.postRv);
        postRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

        firestore = FirebaseFirestore.getInstance();
        mAuth = FirebaseAuth.getInstance();
        currentUser = mAuth.getCurrentUser();
        userId = currentUser.getUid();
    
        firestore.collection("Post")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot documentSnapshot, @Nullable FirebaseFirestoreException e) {
                        if (documentSnapshot != null && !documentSnapshot.getDocuments().isEmpty()) {
                            postList = new ArrayList<>();
                            List<DocumentSnapshot> documents = documentSnapshot.getDocuments();
                            for (DocumentSnapshot value : documents) {
                                Post post = value.toObject(Post.class);
                                postList.add(post);
                            }
                            postAdapter = new PostAdapter(getActivity(), postList);
                            postRecyclerView.setAdapter(postAdapter);
                        }
                    }
                });
    }
}

and let me know if this not works.

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