Android / FireStore查询并返回自定义对象

J. *_* Lo 3 android firebase google-cloud-firestore

我还有一个关于Firestore和Android / Java实现的问题,但这一次是代码。这是我的数据库的样子:

在此处输入图片说明



这将是一个QuizApp,数据库包含生成的ID和。customObject(type: questionDataObject name: content)此外,它还具有带有以下限制/想法的数组列表:

[0]:问题
1:正确答案
[2] ... [4] 错误答案

我为问题数据对象添加了一个字符串“数字”,只是为了让我可以轻松搜索/查询一些内容。那就是我的问题,我无法使查询正常工作。

    public class questionAdder extends AppCompatActivity {

    EditText pQuestion, pAnwerA, pAnswerB, pAnswerC, pAnswerD, number;
    Button pAdd, query;
    private DatabaseReference databaseReference;
    private FirebaseFirestore firebaseFirestore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addquestion);

        firebaseFirestore = FirebaseFirestore.getInstance();

        pQuestion = (EditText) findViewById(R.id.question);
        pAnwerA = (EditText) findViewById(R.id.answerA);
        pAnswerB = (EditText) findViewById(R.id.answerB);
        pAnswerC = (EditText) findViewById(R.id.answerC);
        pAnswerD = (EditText) findViewById(R.id.answerD);
        number = (EditText) findViewById(R.id.number);

        pAdd = (Button) findViewById(R.id.addQuestion);
        pAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                readQuestionStore();
            }
        });

        query = (Button) findViewById(R.id.query);
        query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CollectionReference questionRef = firebaseFirestore.collection("questions");
                com.google.firebase.firestore.Query query = questionRef.whereEqualTo("content.number", "20");
                query.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        //questionObject content = queryDocumentSnapshots.toObjects(questionObject.class);
                    }
                });
            }
        });
    }

    public void readQuestionStore(){
        ArrayList<String> pContent = new ArrayList<>();
        pContent.add(0, pQuestion.getText().toString());
        pContent.add(1, pAnwerA.getText().toString());
        pContent.add(2, pAnswerB.getText().toString());
        pContent.add(3, pAnswerC.getText().toString());
        pContent.add(4, pAnswerD.getText().toString());
        questionObject content = new questionObject(pContent, number.getText().toString()); //document("Essen").collection("Katalog")
       firebaseFirestore.collection("questions").add(content).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Toast.makeText(questionAdder.this, "Klappt", Toast.LENGTH_LONG).show();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(questionAdder.this, "Klappt nicht", Toast.LENGTH_LONG).show();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)


public class questionObject{
    private ArrayList<String> content;
    private String number;

    public questionObject(){

    }

    public questionObject(ArrayList<String> pContent, String pNumber) {
        this.content = pContent;
        this.number = pNumber;
    }

        public ArrayList<String> getContent() {
            return content;
        }

        public void setContent(ArrayList<String> content) {
            this.content = content;
        }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}
Run Code Online (Sandbox Code Playgroud)


这个应用程序什么也不想发布,我只想练习Firebase Firestore编码等。

问题:如何从数据库中获取对象,如何检查查询是否成功?我实际上看不到查询是否找到了我的条目。我唯一的反馈是云引擎添加了“ read”。

谢谢!

Tal*_*rda 5

首先,建议您浏览一下Firestore文档,该文档将指导您有关从Cloud Firestore数据库获取数据的信息。

如果您跳到“ 自定义对象”部分,则会看到以下代码:

DocumentReference docRef = db.collection("cities").document("BJ");
docRef.get().addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
    @Override
    public void onSuccess(DocumentSnapshot documentSnapshot) {
        City city = documentSnapshot.toObject(City.class);
    }
});
Run Code Online (Sandbox Code Playgroud)

这样可以将document snapshot收到的内容转换为custom object。在您的演员表中,您需要将更City.class改为对象questionObject.class


此外,您不能在Array List中将用作属性custom object,因为Firebase module它将无法读取该属性。相反,您必须使用一个Map对象。是Map对象-具有key和的集合value,就像field namevalue中的一样Firestore document

您可以在上面的Firestore文档中看到,在示例数据部分下,他们显示了一个Map示例:

Map<String, Object> data1 = new HashMap<>();
data1.put("name", "San Francisco");
data1.put("state", "CA");
data1.put("country", "USA");
data1.put("capital", false);
data1.put("population", 860000);
Run Code Online (Sandbox Code Playgroud)

这就是为什么您的content媒体资源应如下所示:

Map<Integer, Object> content = new HashMap<>();
content.put(0, "a");
content.put(1, "a");
content.put(2, "a");
content.put(3, "a");
Run Code Online (Sandbox Code Playgroud)

此外,您可以将您Query和您Get request的代码合并为一行代码:

CollectionReference questionRef = firebaseFirestore.collection("questions");
questionRef.whereEqualTo("content.number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
    @Override
    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

    }
});
Run Code Online (Sandbox Code Playgroud)