问题
So im coding an inventory management app and I'm using a barcode scanner to scan my products. My idea is that every time that a product gets scanned I need to remove one quantity of it on my database. Like this: Scan product-->quantity=quantity-1
And this is my code
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFirestore = FirebaseFirestore.getInstance();
scannerView = new ZXingScannerView(this);
setContentView(scannerView);
private void updateData() {
//myresult is the item barcode
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("Items").child(myresult).child("itemquantity");
mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
long qty =(long) dataSnapshot.getValue();
mDatabase.setValue(qty - 1);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
@Override
public void onDestroy() {
super.onDestroy();
scannerView.stopCamera();
}
private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
new AlertDialog.Builder(addquantityactivity.this)
.setMessage(message)
.setPositiveButton("OK", okListener)
.setNegativeButton("Cancel", null)
.create()
.show();
}
@Override
public void handleResult(Result result) {
myResult = result.getText();
Log.d("QRCodeScanner", result.getText());
Log.d("QRCodeScanner", result.getBarcodeFormat().toString());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Scan Result");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
updateData();
scannerView.resumeCameraPreview(addquantityactivity.this);
}
});
builder.setNeutralButton("Visit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(myResult));
startActivity(browserIntent);
}
});
builder.setMessage(result.getText());
AlertDialog alert1 = builder.create();
alert1.show();
}
}
i call updateData()
in my handleResult
function.
The error i get is :
java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Long
回答1:
That's not the right way to decrement the value of a property in Firebase Realtime Database. Because we are creating apps that will be used in a multi-user environment, a more appropriate approach should be the use of transactions as explained in my answer from the following post:
How to save users score in firebase and retrieve it in real-time in Android studio
Or, in a more simpler way:
mDatabase.setValue(ServerValue.increment(-1));
回答2:
Try this :
long qty = dataSnapshot.getValue(Long.class);
来源:https://stackoverflow.com/questions/62635988/firebase-update-an-integer-value