简体   繁体   English

Android / FireStore QuerySnapshot转换为CustomObject

[英]Android/FireStore QuerySnapshot convert to CustomObject

I am currently programin a test QuizApp. 我目前programin测试QuizApp。 The gameplay is pretty easy I just want an online database of questions and a user can answer them. 游戏玩法非常简单我只想要一个问题的在线数据库,用户可以回答它们。

This is what the database looks like: 这就是数据库的样子:
在此输入图像描述

That collection questions contains an unique ID and a custom Object (questionObject) named 'content'. 该集合问题包含唯一ID和名为“content”的自定义对象(questionObject)。 The number is only something easy I can query/search for. 这个数字只是我可以查询/搜索的简单内容。

This is my questionAdder and query UI. 这是我的问题添加和查询UI。 It's only a small test App. 这只是一个小测试App。

public class questionAdder extends AppCompatActivity { public class questionAdder扩展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");
            questionRef.whereEqualTo("content.number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);
                }
            });
        }
    });

}

public void readQuestionStore(){

    Map<String, Object> pContent = new HashMap<>();
    pContent.put("question", pQuestion.getText().toString());
    pContent.put("Corr Answer", pAnwerA.getText().toString());
    pContent.put("AnswerB", pAnswerB.getText().toString());
    pContent.put("AnswerC", pAnswerC.getText().toString());
    pContent.put("AnswerD", 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();
        }
    });
}

} }



And this is how my questionObject looks like: 这就是我的questionObject的样子:

public class questionObject{ public class questionObject {

private Map<String, Object> content;
private String number;

public questionObject(){

}

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

public Map<String, Object> getContent() {
    return content;
}

public void setContent(Map<String, Object> content) {
    this.content = content;
}

public String getNumber() {
    return number;
}

public void setNumber(String number) {
    this.number = number;
}

} }



Problem In that questionAdder class in the onClickListener I receive an "incompatible types" Error (Found: java.utils.list Required: questionObject). 问题在onClickListener中的questionAdder类中我收到“不兼容类型”错误(找到:java.utils.list必需:questionObject)。

query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CollectionReference questionRef = firebaseFirestore.collection("questions");
                questionRef.whereEqualTo("content.number", "20").get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                    @Override
                    public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                        questionObject pContent = queryDocumentSnapshots.toObjects(questionObject.class);
                    }
                });
            }
        });

If if I change that to a List it is empty. 如果我将其更改为List,则为空。 So the actual question is, how do I get the CustomObject into my code using the Database. 所以实际的问题是,如何使用数据库将CustomObject放入我的代码中。 Thanks! 谢谢!

The reason you are getting this error in because the QuerySnapshot is a type which "contains" multiple documents. 您收到此错误的原因是因为QuerySnapshot是一种“包含” 多个文档的类型。 Firestore won't decide for you whether there are a bunch of objects to return as a result, or just one. Firestore不会决定是否有一堆对象要返回,或者只返回一个。 This is why you can take two different approaches: 这就是为什么你可以采取两种不同的方法:

  1. Put the data in a custom object 's list: 将数据放在custom object的列表中:

     List<questionObject> questionsList=new ArrayList<>(); if (!documentSnapshots.isEmpty()){ for (DocumentSnapshot snapshot:queryDocumentSnapshots) questionsList.add(snapshot.toObject(questionObject.class)); } 
  2. If you're sure that your gonna get only one queried object, you can just get the first object from the returned queryDocumentSnapshots : 如果您确定只获得一个查询对象,则可以从返回的queryDocumentSnapshots获取第一个对象:

     questionObject object=queryDocumentSnapshots.getDocuments().get(0).toObject(questionObject.class); 

A few more things you should be aware of: 还有一些你应该注意的事情:

Why do you write content.number instead of just number ? 为什么要写content.number而不仅仅是number It seems like number is a separated field in your question document , so your code should be as follows: 似乎number是问题document的单独字段,因此您的代码应如下所示:

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

In addition, try to change your number field to int , because it's not a String but a just a number. 另外,尝试将您的number字段更改为int ,因为它不是String而只是一个数字。

By the way, it is more acceptable to write classes' names with a capital letter at a beginning, for example: QuestionObject question=new QuestionObject(); 顺便说一句,在开头用大写字母编写类的名称是更可接受的,例如: QuestionObject question=new QuestionObject();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 "如何从 android firestore 中的 QuerySnapshot 获取密钥" - How to get key from QuerySnapshot in android firestore 转换列表 <CustomObject> 到了json - convert List<CustomObject> to json 如何检查Cloud Firestore集合是否存在? (querysnapshot) - How to check if Cloud Firestore collection exists? ( querysnapshot) 是否可以将CustomObject []转换为String []而无需迭代? - Is it possible to convert CustomObject[] to String[] without iteration? 你能转换一个Java Map吗? <Long,CustomObject> 到byte []然后回到Map <Long,CustomObject> ? - Can you convert a Java Map<Long,CustomObject> to byte[] then back to Map<Long,CustomObject>? Spark Streaming 转换数据集<row>到数据集<customobject>在 java</customobject></row> - Spark Streaming Convert Dataset<Row> to Dataset<CustomObject> in java Android Firestore将文档引用数组转换为List <Pojo> - Android Firestore convert array of document references to List<Pojo> Firebase Firestore:如何在Android上将文档对象转换为POJO - Firebase Firestore : How to convert document object to a POJO on Android Recyclerview 适配器:java.util.ArrayList 无法强制转换为 com.google.ZBF12E1525C25C7AB9A15com.google.ZBF12E1525C25C7AB9A15Z.firestore.F1413SnapshotA15查询 - Recyclerview Adapter: java.util.ArrayList cannot be cast to com.google.firebase.firestore.QuerySnapshot 如何避免对使用带有 firestore 的 snapshotListener 删除的消息调用 onEvent(QuerySnapshot snapshots, FirestoreException error)? - How to avoid call onEvent(QuerySnapshot snapshots, FirestoreException error) for message deleted using the snapshotListener with firestore?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM