Android中FireStore QuerySnapshot转换为自定义对象的实现方案问询
Hey there! Let's get that QuerySnapshot converted to your custom questionObject sorted out—here's a step-by-step guide tailored to your QuizApp setup:
First, make sure your custom objects align with your Firestore questions collection structure. From your description, each document has a unique ID, a number field, and a content field that's your custom questionObject (holding the question text and options).
Here's how to structure these classes properly (Firestore requires no-arg constructors and getter methods for deserialization):
// This is your `questionObject` that maps to the `content` field in Firestore public class QuestionContent { private String questionText; private String answerA; private String answerB; // Add other option fields (answerC, answerD) or a correctAnswer field as needed // Required no-arg constructor for Firestore public QuestionContent() {} // Convenience constructor for creating new content objects public QuestionContent(String questionText, String answerA, String answerB) { this.questionText = questionText; this.answerA = answerA; this.answerB = answerB; } // Getter methods for all fields (Firestore needs these to read data) public String getQuestionText() { return questionText; } public String getAnswerA() { return answerA; } public String getAnswerB() { return answerB; } // Add getters for any additional fields you have } // This class maps to the entire document in your `questions` collection public class Question { @DocumentId // Maps Firestore's document ID to this field private String id; private int number; private QuestionContent content; // Required no-arg constructor public Question() {} // Convenience constructor public Question(String id, int number, QuestionContent content) { this.id = id; this.number = number; this.content = content; } // Getter methods public String getId() { return id; } public int getNumber() { return number; } public QuestionContent getContent() { return content; } }
Once your data classes are set up, converting a QuerySnapshot is straightforward using Firestore's built-in toObject() method. Here's how to implement this in your questionAdder class (or wherever you handle Firestore queries):
// Inside your questionAdder class, e.g., in a button click listener or initialization code FirebaseFirestore db = FirebaseFirestore.getInstance(); // Query all questions in the collection (adjust the query as needed, e.g., whereEqualTo("number", 5)) db.collection("questions") .get() .addOnCompleteListener(task -> { if (task.isSuccessful()) { List<Question> questionList = new ArrayList<>(); // Iterate through each document in the QuerySnapshot for (QueryDocumentSnapshot document : task.getResult()) { // Convert the document directly to your Question object Question question = document.toObject(Question.class); questionList.add(question); // Optional: If you need to manually access the document ID (though @DocumentId handles this) // String docId = document.getId(); // question.setId(docId); // Add a setter to the Question class if you need this } // Now you can use the questionList for your app's logic // Example: Log the first question's text if (!questionList.isEmpty()) { Log.d("QuizApp", "First Question: " + questionList.get(0).getContent().getQuestionText()); } } else { Log.w("QuizApp", "Failed to fetch questions", task.getException()); } });
- No-arg Constructors: Firestore needs these to create instances of your classes during deserialization—don't skip them!
- Field Matching: Ensure your class field names exactly match the keys in your Firestore documents. If they don't, use the
@PropertyName("firestore_key_name")annotation to map them (e.g.,@PropertyName("question_text") private String questionText;). - Nested Objects: If your
questionObjecthas its own nested objects, apply the same rules (no-arg constructor, getters) to those classes too. - Direct Content Extraction: If you only need the
contentfield (not the full document), you can pull it directly:QuestionContent content = document.get("content", QuestionContent.class);
内容的提问来源于stack exchange,提问作者J. Lo

