[英]How to store array in firestore database using Android?
I want to create an firestore model like below:我想创建一个如下所示的 Firestore 模型:
attendance_log (root collection)
|
|--- 001 (document ID)
| |
| |--- date : 20190310
| |--- time : 1025
| |--- subject : "Android Programming"
| |--- present : {"MCA01", "MCA03", "MCA04"}
| |--- absent : {"MCA02, "MCA05"}
I could store date, time and subject by passing the value in a Map as below :我可以通过在 Map 中传递值来存储日期、时间和主题,如下所示:
Map<String, Object> attend = new HashMap<>();
attend.put("date", d) ;
attend.put("time", t) ;
attend.put("subject", subject) ;
db.collection("attendance_log")
.document(docID)
.set(attend)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid){
Toast.makeText(TakeAttendance.this,"Attendance added sucessfully" , Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Snackbar.make(findViewById(R.id.cdlayout) ,"Something went wrong!", Snackbar.LENGTH_LONG).show();
}
});
But passing the array generates the error但是传递数组会产生错误
java.lang.IllegalArgumentException: Could not serialize object. Serializing Arrays is not supported, please use Lists instead
The solution is in your error - you need to read your error and check what does it say - in your case, you will see that Arrays are not supported and you need to send list instead.解决方案是您的错误 - 您需要阅读错误并检查它说了什么 - 在您的情况下,您将看到不支持数组,您需要发送列表。
You can use Arrays.asList(yourArray)
to convert your array and send it to your database.您可以使用Arrays.asList(yourArray)
转换数组并将其发送到数据库。
Change this line:更改此行:
attend.put("subject", subject) ;
To This line:到这一行:
attend.put("subject", Arrays.asList(subject)) ;
No need to worry you are very near to the correct code.无需担心您非常接近正确的代码。 In firestore you can store array String[] instead you have to use List:在 firestore 中,您可以存储数组 String[] 而不是必须使用 List:
//convert array to arraylist
ArrayList<String> subjectsArrayList = getListOfSubjects(subjects);
Map<String, Object> attend = new HashMap<>();
attend.put("date", d) ;
attend.put("time", t) ;
attend.put("subject", subject) ;
hashMap.put("subjects", subjectsArrayList);
db.collection("attendance_log")
.document(docId)
.update(attend)
.addOnCompleteListener(task -> {
//done
});
Here is getListOfSubjects
method这是getListOfSubjects
方法
public ArrayList<String> getListOfSubjects(String[] subjects){
List<String> subjectsArrayList = new ArrayList<>();
for (int i = 0; i < subjects.length; i++) {
subjectsArrayList.add(subjects[i]);
}
return (ArrayList<String>) subjectsArrayList;
}
Hope this will help you.希望这会帮助你。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.