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

标签 android firebase google-cloud-firestore

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

enter image description here



这将是一个 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();
            }
        });
    }
}


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

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

谢谢!

最佳答案

首先,我建议您查看此 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);
    }
});

这是将收到的文档快照转换为自定义对象的方法。在您的转换中,您需要将 City.class 更改为您的对象,即 questionObject.class


此外,您不能将Array List 用作自定义对象 中的属性,因为Firebase 模块 不会能够阅读那个。相反,您必须使用 Map 对象。 This是 Map 对象 - 一个具有 keyvalue 的集合,就像 field namevalueFirestore 文档 中。

您可以在上面的 Firestore 文档中看到,在 Example Data 部分下,他们显示了一个 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 请求 组合到一行代码中:

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

    }
});

关于Android/FireStore 查询并返回自定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49592124/

相关文章:

android - 我们有办法将完整源代码包含到 APK 中吗?

java - 测试应用程序时出错 - Firebase 测试实验室

typescript - 从 onCreate 的 Firestore snap.data 检索数据但出现未定义的错误

flutter - 我想在我的水平 ListView 之后添加一个新元素我该如何添加它

android - 跟踪移动本地数据库和可选云数据库之间的已删除条目

java - 插件Android支持中的异常(exception)-元素的内容必须包含格式正确的字符数据或标记

android - 如何在 Android 中动态创建按钮?

android - Firebase 在 Android 中使用子数据检索父数据

firebase - 有没有一种方法可以更新 Firebase Cloud Message (FCM) 发送到 Web 应用程序的通知,而不是创建新通知?

android - 为什么 $cordova ImagePicker 插件在 Marshmallow 上崩溃?