I am trying to make an application on Android, I am a beginner.
I try to increment the "stock" of a product, but my following code is not reliable. I had connection problems on the device and the "stock" did not increase correctly. How can I execute it as a transaction?. I cannot find extensive documentation.
final HashMap<String, BigDecimal> detalle = new HashMap<String, BigDecimal>();
Query query = mDatabase.child("COMPRAS").child(key).child("COMPRASPRODUCTO");
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
CompraProducto producto = ds.getValue(CompraProducto.class);
detalle.put(producto.getId(),new BigDecimal(producto.getCantidad()));
}
for (String key : detalle.keySet()) {
Query queryp = mDatabase.child("PRODUCTO").child(key);
queryp.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot data) {
Producto p = data.getValue(Producto.class);
try{
stockOriginal = new BigDecimal(p.getStock());
mProductoProvider = new productoProvider();
mProductoProvider.refreshStock(p.getCodigo(), stockOriginal.add(detalle.get(p.getCodigo())).toString()).addOnSuccessListener(new OnSuccessListener<Void>() {
@Override
public void onSuccess(Void aVoid) {
}
});
}catch(Exception e){
Toast.makeText(comprarProducto.this, "Producto " + data.getKey() + " no existe.", Toast.LENGTH_LONG).show();
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
});
Thank you.