'Android & Firestore - deducting value from an object
General context: The app I'm making manages activities with resources at hand. Once users create cases, the amount of materials each case needs is deducted from the inventory of materials.
What I'm trying to do: I've saved the materials on Firestore and would like to deduct the quantity of the material used up by a case from the saved quantity. Here's the model class:
data class Material(
var type: String = "",
var material: String = "",
var size: String = "",
var description: String = "",
var unit: String = "",
var quantity: String = "0",
var actualquantity: String = "0" /*actual is the confirmed quantity*/) :FireStoreData()
My attempt: I've tried to save the list of materials needed for a case, exitingMaterials, and search each of them in the database, then merge them to a new Material object that has the updated quantity, as follows:
//region DEDUCTION: DIFFERENT APPROACH
for (Material material : exitingMaterials) {
db.collection("materials")
.whereEqualTo("type", material.getType())
.whereEqualTo("material", material.getMaterial())
.whereEqualTo("description", material.getDescription())
.whereEqualTo("size", material.getSize())
.get()
.addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
@Override
public void onComplete(@NonNull Task<QuerySnapshot> task) {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
Material currentMaterial = document.toObject(Material.class);
try {
db.collection("materials").document(document.getId()).set(
new Material(
material.getType(),
material.getMaterial(),
material.getSize(),
material.getDescription(),
material.getUnit(),
("" + (Integer.parseInt(currentMaterial.getQuantity()) - Integer.parseInt(material.getQuantity()))),
material.getActualquantity()
), SetOptions.merge()
);
} catch (Exception e) {
Toast.makeText(context, "Couldn't subtract", Toast.LENGTH_LONG).show();
}
Log.d(TAG, document.getId() + " => " + document.getData());
}
} else {
Log.d(TAG, "Error getting documents: ", task.getException());
Toast.makeText(context, "Task Unsuccessful!", Toast.LENGTH_LONG).show();
}
}
});
}
//end region
However, I'm not getting any feedback from the app. The task says deduction is successful, but the firestore data remains unchanged. What am I missing?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|