从Firestore检索所有文档作为自定义对象

时间:2018-07-16 12:34:06

标签: 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课:

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

1 个答案:

答案 0 :(得分:1)

要解决此问题,无需两次获取数据。您可以通过仅使用一次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