Reputation: 65
I have the following situation, namely:
I get documents from a database and convert them to objects:
Code:
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();
}
}
});
}
Structure:
Then I display products in RecyclerView:
Going to the merits, I would like the user to be able to change the specifics of the product, and precisely its weight, which will automatically change the other values (calories, protein etc.).
Therefore, after clicking on a given item RecyclerView I go to an activity in which the user can make changes to the product. How can I associate a given product that the user has chosen with the corresponding product in CloudFirestore? That changes would also take place in the document.
I was thinking about incrementing the product ID then I could associate the product with the product position in ReyclerView but I read that it is not good practice or is there any other way?
Upvotes: 0
Views: 99
Reputation: 80914
If the user clicks on an item, then send the name to the other activity and then do a query:
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());
}
}
}
});
Use the query whereEqualTo
to query that will return all names
with the name Chicken breast meat
, then after task is successful update the document with the data that the user entered.
https://firebase.google.com/docs/firestore/query-data/queries
https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document
Upvotes: 1