【问题标题】:Getting all documents from one collection in cloud Firestore?从云 Firestore 中的一个集合中获取所有文档?
【发布时间】:2020-05-30 06:52:17
【问题描述】:

我开始学习 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

【问题讨论】:

  • Arman Abdulun 有什么问题
  • 请将您的数据库结构添加为屏幕截图。也请回复@AlexMamo
  • 我更正了我的问题并添加了截图

标签: java android firebase google-cloud-firestore


【解决方案1】:

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

如果这不起作用,请告诉我。

【讨论】:

  • 注意使用 addSnapshotListener() 将继续监听值,每当值更改时,它都会触发您的 onEvent 回调,.addOnCompleteListener 将是一次性获取操作
  • 感谢您的帮助,但我无法理解如何将其添加到我的代码中,您可以解释如何将带有官方文档的代码添加到我的代码中
  • @ArmanAbdullin 查看此更新的 sn-p,如果您仍有疑问,请告诉我。
  • Arindam Karmakar 非常感谢您,您的代码有效,您帮了我很多。以后可以联系你吗?提前致谢。
  • 您好,感谢您的帮助,但您可以提供其他帮助。 Tama 与我使用您的代码获取 Post 的方法相同,但如何在此处获取值。提前致谢
猜你喜欢
  • 2019-02-05
  • 1970-01-01
  • 2020-08-08
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
相关资源
最近更新 更多