I am new to Firestore. I have problem in retrieving all the documents from Firestore as custom objects (here its the object Qst). Please help me.
I'm using Cloud Firestore as follows:
And my code is :
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());
}
}
});
and here is my 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;
}}
To solve this, there is not need to get the data twice. You can achieve this, by only using a get() call once. So please use the following lines of code:
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());
}
}
}
});
The output in your logcat will be:
In what year was Google launched on the web?
//and so on
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.