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

时间:2018-03-31 20:31:13

标签: android firebase google-cloud-firestore

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

enter image description here



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

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

我在questionDataObject中添加了一个String“number”,只是为了让我可以搜索/查询一些简单的东西。这是我的问题,我无法使查询正常工作。

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


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


这个应用程序不是我想要发布的,我只是想练习Firebase Firestore编码等。

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

谢谢!

1 个答案:

答案 0 :(得分:3)

首先,我建议您浏览此Firestore documentation,它将指导您从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);
    }
});

这是您将收到的document snapshot投射到custom object的方法。在演员表中,您需要将City.class更改为您的对象,即questionObject.class

此外,您无法在Array List中使用custom object作为属性,因为Firebase module将无法读取该内容。相反,您必须使用Map对象。 This是地图对象 - 具有keyvalue的集合,就像field name {valueFirestore一样{1}}。

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

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); 属性应该是这样的:

content

此外,您可以将Map<Integer, Object> content = new HashMap<>(); content.put(0, "a"); content.put(1, "a"); content.put(2, "a"); content.put(3, "a"); Query合并为一行代码:

Get request