Android Firestore将hashmaps添加到Firestore中的映射字段
我正在尝试使用键->值对在firestore数据库中创建对象的映射。 我们的想法是在我的属性文档中有一个房间对象的地图,其中客厅是关键,并且是具有价值的对象。如下图所示 我对将对象添加到firestore中的正确方法感到迷茫,因为房间地图已经在那里了,所以我如何向其中添加密钥->值对?? 我还需要执行下面代码中的搜索,以便抓取属性文档并将对象添加到房间地图字段中Android Firestore将hashmaps添加到Firestore中的映射字段,android,google-cloud-firestore,Android,Google Cloud Firestore,我正在尝试使用键->值对在firestore数据库中创建对象的映射。 我们的想法是在我的属性文档中有一个房间对象的地图,其中客厅是关键,并且是具有价值的对象。如下图所示 我对将对象添加到firestore中的正确方法感到迷茫,因为房间地图已经在那里了,所以我如何向其中添加密钥->值对?? 我还需要执行下面代码中的搜索,以便抓取属性文档并将对象添加到房间地图字段中 FirebaseFirestore db = FirebaseFirestore.getInstance(); final Col
FirebaseFirestore db = FirebaseFirestore.getInstance();
final CollectionReference propertyRef = db.collection("Properties");
final Room room = new Room(roomName, feet, inches, imageUrl);
propertyRef.whereEqualTo("propertyId", propertyId).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot doc : Objects.requireNonNull(task.getResult())) {
propertyRef.document(doc.getId())
-----> .update("rooms", ""+roomName+"", room);
Log.d(TAG, "Firebase Success= " + imageUrl);
Toast.makeText(CreatePropertyActivity3.this, "Property Created", Toast.LENGTH_LONG).show();
exProperties();
}
} else {
Toast.makeText(CreatePropertyActivity3.this, "Error check log", Toast.LENGTH_LONG).show();
}
}
});
FirebaseFirestore db=FirebaseFirestore.getInstance();
最终收集参考属性ref=db.collection(“属性”);
最终房间=新房间(房间名称、英尺、英寸、图像URL);
propertyRef.whereEqualTo(“propertyId”,propertyId).get().addOnCompleteListener(新OnCompleteListener()){
@凌驾
未完成的公共void(@NonNull任务){
if(task.issusccessful()){
对于(QueryDocumentSnapshot文档:Objects.requireNonNull(task.getResult())){
propertyRef.document(doc.getId())
----->.更新(“房间”,“房间名+”,房间);
Log.d(标签,“Firebase成功=“+imageUrl”);
Toast.makeText(CreatePropertyActivity3.this,“Property Created”,Toast.LENGTH_LONG.show();
exproperty();
}
}否则{
Toast.makeText(CreatePropertyActivity3.this,“错误检查日志”,Toast.LENGTH_LONG.show();
}
}
});
在db
上使用文档(字符串)
方法,如果文档不存在()
事实上,因为您使用的是
whereEqualTo
,所以您总是获取对同一文档的引用并覆盖其内容。只需使用add()
功能,查看文档以了解更多示例。希望有帮助 我很抱歉没有解释清楚,请看我更新的问题。我正在使用whereEqualTo获取正确的属性文档,这样我就可以添加到该文档中的房间地图字段中
Map<String, Object> room = new HashMap<>();
room.put("feet", "...");
...
db.collection("rooms").document("the new room id")
.set(room)
.addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
...
}
})
.addOnFalureListener(...)
final HashMap<String, Object> newRoom = new HashMap<>();
newRoom.put(roomName, room);
...
propertyRef.add(newRoom)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
@Override
public void onSuccess(DocumentReference documentReference) {
Log.d(TAG, "DocumentSnapshot written with ID: " + documentReference.getId());
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.w(TAG, "Error adding document", e);
}
});