【问题标题】:Android/FireStore Querying and returning a custom ObjectAndroid/FireStore 查询并返回自定义对象
【发布时间】:2018-03-31 20:31:12
【问题描述】:

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



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

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

我在 questionDataObject 中添加了一个字符串“数字”,只是为了让我可以轻松搜索/查询。这是我的问题,我无法让查询正常工作。

    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 编码等。

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

谢谢!

【问题讨论】:

    标签: android firebase google-cloud-firestore


    【解决方案1】:

    首先,我建议您阅读此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 是 Map 对象 - 一个包含 keyvalue 的集合,就像 Firestore document 中的 field namevalue 一样。

    您可以在上面的 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);
    

    这就是为什么您的 content 属性应该如下所示:

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

    此外,您可以将QueryGet request 组合成一行代码:

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

    【讨论】:

    • 感谢您的快速响应。我找到了关于获取数据的部分,但我不确定如何将查询与它结合起来。我在按钮查询的 On Click 侦听器中有该代码,这在理论上是否正确?我划掉了 .toObject 部分,因为我确实收到了 ArrayList 不兼容错误。我将删除数组并添加一个哈希图作为第一步!
    • 是的,将您的听众放在OnClickListener 中是一种选择。如果要执行更多代码,它也可以在单独的method 中。确保在请求开始时显示进度条,并在完成时禁用它,以便用户了解其状态。
    • 抱歉,我描述错了。我想问一下 OnClickListener 中的查询和获取命令是否正确。 Firebase 文档仅描述了仅获取或仅查询示例,但我想查询和获取。抱歉,我不是母语人士,希望我现在可以更好地描述它。
    • @J.Lo 我已经编辑了我的答案并添加了查询和获取的组合版本。我希望它能回答你的问题。你可以把它放在你的OnClickListener
    • 我现在改变了 questionObject,它得到了数字和一个 HashMap。我还编辑了 Query-Button-OnClickListenor,但是在尝试将 Snapchot 转换为我的对象时: questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);它给了我一个不兼容的类型错误。找到 java.util.list 和必需:questionObject.
    猜你喜欢
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2017-08-11
    • 1970-01-01
    • 2019-11-28
    • 2018-11-14
    • 2021-05-02
    • 1970-01-01
    相关资源
    最近更新 更多