从Cloud Firestore中的一个集合中获取所有文档?

时间:2020-02-14 13:03:03

标签: java android firebase google-cloud-firestore

我开始学习Android并尝试解决数小时的问题。也许有人会向我解释如何从收藏集中获取所有文档->从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);
            }
        });
    }
}

通常,阅读一切都写得很好的官方文档非常有用。

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());
            }
        }
    });

此代码已建议给我。我不知道如何将其嵌入代码中。

enter image description here

1 个答案:

答案 0 :(得分:2)

使用 addSnapshotListener()方法将所有文档收集到一个集合中

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;
                                }
                            }
                        }
                    }
                }
            });

代码:

public class HomeFragment extends Fragment {

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

FirebaseAuth mAuth;
FirebaseUser currentUser;

List<Post> postList;

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);
                    }
                }
            });
}

让我知道这是否行得通。