java如何使用Firestore向文档中的哈希映射数组添加数据?
我希望在不覆盖的情况下将数据添加到现有阵列。在每个文档中,我有一个数组HashMap
。我正在尝试向现有数据添加数据。请检查下面的代码,并提供一些信息
public void createNewCase(){
Map<String, String> caseInfo = new HashMap<String, String>();
caseInfo.put("chief_complaint", chiefComplaintET.getText().toString());
caseInfo.put("facility", facilityET.getText().toString());
caseInfo.put("location", locationET.getText().toString());
caseInfo.put("assigned_provider", assignProviderET.getText().toString());
caseInfo.put("referring_provider", referringProviderET.getText().toString());
caseInfo.put("admit_date", adminDateET.getText().toString());
caseDictionary.add(caseInfo);
final String patientID = sharedPrefHelper.getStr("patient_id");
db.collection("patients").whereEqualTo("patient_id", patientID).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
private static final String TAG = "New Case Creation" ;
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
List<HashMap<String,String>> list = new ArrayList<>();
for (QueryDocumentSnapshot document : task.getResult()) {
patient patient = new patient();
list = (List) document.get("patient_case");
for (HashMap<String, String> item:list) {
caseDictionary.add(item);
}
}
System.out.println(caseDictionary);
HashMap<String, Object> uploadData = new HashMap<>();
uploadData.put("patient_case", caseDictionary);
DocumentReference caseRef = db.collection("patients").document(patientID); // am stuck here
}else{
Log.w(TAG, "Error getting documents.", task.getException());
Toast.makeText(NewCase.this, "Something bad happened", Toast.LENGTH_SHORT).show();
Helper.m_Dialog.hide();
}
}
});
}
编辑1 下面的代码删除旧数据并添加新数据。我需要追加
final String patientID = sharedPrefHelper.getStr("patient_id");
final CollectionReference collectionReference = db.collection("patients");
collectionReference.whereEqualTo("patient_id", patientID).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
Toast.makeText(NewCase.this, task.getResult().toString(), Toast.LENGTH_SHORT).show();
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Map<Object, Object> map = new HashMap<>();
map.put("patient_case", caseInfo);
collectionReference.document(document.getId()).set(map, SetOptions.merge());
}
}else{
Toast.makeText(NewCase.this, task.getResult().toString(), Toast.LENGTH_SHORT).show();
}
}
});
# 1 楼答案
这是我的一个例子
我是这样做的
历史是我的一门课
历史类包括方法toMap(),该方法将所有历史类变量及其值转换为“Key”:“value”形式,如下所示
# 2 楼答案
正如我在您的屏幕截图中看到的,在
patients
集合中,您的文档包含一个包含贴图(对象)的数组。为了能够更新数组中存在的映射,您应该创建一个Map
对象,该对象对应于您的确切文档结构,并使用DocumentReference的set(Object data, SetOptions options)方法进行更新。因此,将map作为第一个参数传递,并作为第二个参数SetOptions.merge()
。你可以在我的回答中从下面的帖子中找到一个更简单的例子: