java - 从 firestore 中检索所有文档作为自定义对象

标签 java android firebase google-cloud-firestore

我是 Firestore 新手。我在从 Firestore 检索所有文档作为自定义对象(此处为对象 Qst)时遇到问题。请帮助我。

I'm using Cloud Firestore as follows:

我的代码是:

db.collection("questions")
            .get()
            .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                @Override
                public void onComplete(@NonNull Task<QuerySnapshot> task) {
                    if (task.isSuccessful()) {
                        for (DocumentSnapshot document : task.getResult()) {
                           // Log.d("state", document.getId() + " => " + document.getData());
                            db.collection("questions").document(document.getId())
                                    .get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
                                @Override
                                public void onSuccess(DocumentSnapshot documentSnapshot) {
                                    Qst q=documentSnapshot.toObject(Qst.class);
                                    Log.d("qst",q.toString());
                                }
                            });
                        }
                    } else {
                        Log.d("state", "Error getting documents: ", task.getException());
                    }
                }
            });

这是我的 Qst 类(class):

public class Qst {

private String qst;
private String[] choiceList;
private int ansIndex;

public Qst(String qst, String[] choiceList, int ansIndex) {
    this.qst = qst;
    this.choiceList = choiceList;
    this.ansIndex = ansIndex;
}}

最佳答案

要解决这个问题,不需要两次获取数据。您只需使用一次 get() 调用即可实现此目的。因此,请使用以下代码行:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference questionsRef = rootRef.collection("questions");
questionsRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (DocumentSnapshot document : task.getResult()) {
                Qst qst = document.toObject(Qst.class);
                Log.d("TAG", qst.getQst());
            }
        }
    }
});

logcat 中的输出将是:

In what year was Google launched on the web?
//and so on

关于java - 从 firestore 中检索所有文档作为自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361951/

相关文章:

Java Mac appbundle 资源路径

java - 线程帮助与 Android 游戏

java - 访问已创建 View 的同一实例

java - 如何仅使用本地主机 :8080 address. 运行 servlet 应用程序,这意味着我不想使用任何 url 模式

java - 不同的默认 'initialCapacity' HashSet 和 LinkedHashSet

java - 在java中找出增加或减少的单调数组

Android - Twitter - 获取接下来的 20 个提要以及接下来的 20 个和接下来的 20 个

firebase - 应用程序图标徽章 - Firebase 推送通知/FCM - Flutter

javascript - 为什么我的 Firebase 请求返回 500(内部服务器错误)?

firebase - 从Google Sheets脚本重新排列Firebase实时数据库中显示的值