0

I am facing a problem of how to exactly use Firebase Transaction runTransaction() method. Here when the user clicks the button I am trying to fetch the value from database and increment it and then again send it back to database. Now issue is what if multiple users tap the button at the same time, for this I am using Firebase transaction. But don't know exactly how to write the code. Here is the code which I have tried but not working. I just want to update the value from 0 to 1, if button is clicked by only one user and if clicked simultaneously by many users, then one of the user should wait until the first user completes the updating.

myRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(final DataSnapshot dataSnapshot) {
            final String mainValue = (String) dataSnapshot.child("values").child("number").getValue();

            btnInc.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    myRef.runTransaction(new Transaction.Handler() {
                        @Override
                        public Transaction.Result doTransaction(final MutableData mutableData) {
                            mutableData.child("number").setValue(String.valueOf(Integer.parseInt(mainValue) + 1));
                            return Transaction.success(mutableData);
                        }

                        @Override
                        public void onComplete(DatabaseError databaseError, boolean b, DataSnapshot dataSnapshot) {

                            Toast.makeText(MainActivity.this, "Result: "+b, Toast.LENGTH_SHORT).show();

                            Toast.makeText(MainActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            });
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });

enter image description here

Here is my database screenshot

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
Kaushal
  • 217
  • 1
  • 4
  • 12
  • You should read [the docs](https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions) about transactions. The way you are currently doing it is completely different from how you should do a transaction. – André Kool Mar 13 '18 at 09:01
  • Possible duplicate of [How to save users score in firebase and retrieve it in real-time in Android studio](https://stackoverflow.com/questions/48307610/how-to-save-users-score-in-firebase-and-retrieve-it-in-real-time-in-android-stud) – Alex Mamo Mar 13 '18 at 13:10

0 Answers0