我有以下情况,即:
我从数据库获取文档并将它们转换为对象:
代码:
private void getProductsFromDatabaseBreakfast() {
breakfastProducts.clear();
firebaseFirestore.collection("Users").document(currentUserUID)
.collection("Types of Meals").document("Breakfast")
.collection("Date of Breakfast").document(date)
.collection("List of Products")
.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()) {
for(DocumentSnapshot documentSnapshot: task.getResult().getDocuments()) {
Log.i("id", documentSnapshot.getId());
breakfastProducts.add(documentSnapshot.toObject(Product.class));
}
}
if(getFragmentRefreshAdapter() != null) {
getFragmentRefreshAdapter().onRefresh();
}
}
});
}
结构:
然后我在 RecyclerView 中显示产品:
说到优点,我希望用户能够更改产品的细节,以及精确的重量,这将自动更改其他值(卡路里、蛋白质等)。
因此,在单击给定项目 RecyclerView 后,我会转到用户可以对产品进行更改的 Activity 。如何将用户选择的给定产品与 CloudFirestore 中的相应产品关联起来?该更改也将发生在文档中。
我正在考虑增加产品 ID,然后我可以将产品与 ReyclerView 中的产品位置相关联,但我读到这不是一个好的做法,或者还有其他方法吗?
最佳答案
如果用户单击某个项目,则将名称发送到其他 Activity ,然后执行查询:
CollectionReference ref = firebaseFirestore.collection("Users").document(currentUserUID)
.collection("Types of Meals").document("Breakfast")
.collection("Date of Breakfast").document(date)
.collection("List of Products");
ref.whereEqualTo("name", name).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if(task.isSuccessful()) {
for(DocumentSnapshot documentSnapshot: task.getResult().getDocuments()) {
Map<String, Object> data = new HashMap<>();
data.put("weight", 200);
ref.document(documentSnapshot.getId()).set(data, SetOptions.merge());
}
}
}
});
使用查询 whereEqualTo
进行查询,将返回所有名称为 Chicken chest milk
的 names
,然后在任务成功后更新文档与用户输入的数据。
https://firebase.google.com/docs/firestore/query-data/queries
https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document
关于java - 如何将 RecyclerView 中显示的数据与 Firebase 中的文档关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59173977/