0

I am new to mobile android development. I am trying to build an library management application. Here I have two admins ,who can modify the database (realtime database, firebase).I tried the following code to handle the case when both admins try to alter the database simultaneously:

  int books= Integer.parseInt(addBooks.getText().toString());
  String isbn=isbnNo.getText().toString();
 DatabaseReference ref=reference.child("books").child(isbn).child("bookCount");
 ref.runTransaction(new Transaction.Handler() {
     @NonNull
     @Override
     public Transaction.Result doTransaction(@NonNull MutableData  mutableData) {
         Integer currentBookCount=mutableData.getValue(Integer.class);
         mutableData.setValue(currentBookCount+books);
         return Transaction.success(mutableData);
     }

     @Override
     public void onComplete(@Nullable DatabaseError error, boolean committed, @Nullable DataSnapshot currentData) {
         Toast.makeText(getApplicationContext(),"Added successfully",Toast.LENGTH_LONG).show();
     }
 });

My database looks like this:

this

It shows "Added successsfully" messages in both the devices when I run simultaneously, but is not upadating the final answer in the database.I am also not sure if this approach is appropriate, any help is appreciated.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
Bhanu
  • 5
  • 3

1 Answers1

0

If you want to do a simple increment (or decrement) operation, Firebase has a much easier solution for that these days with a built in increment() operation.

For that it is important that you store the value as a number though, and not as a string as you have it now. Once you store it as a number, you can increment the bookCount by books with:

int books= Integer.parseInt(addBooks.getText().toString());
String isbn=isbnNo.getText().toString();
DatabaseReference ref=reference.child("books").child(isbn).child("bookCount");
ref.setValue(ServerValue.increment(books));

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • 1
    Thanks, this solution works. I also want to add one more condition that the bookCount shouldn't exceed 100. Is it possible to add such condition by using ServerValue.increment()? – Bhanu Mar 27 '21 at 09:39
  • Not in the code itself, but you could do that in the server-side security rules. See https://firebase.google.com/docs/firestore/security/rules-conditions#data_validation. If you're having trouble making that work, I'd recommend posting a new question with its own reproduction. – Frank van Puffelen Mar 27 '21 at 14:23