1

My application was token generation mobile application. Iam using Firebase to store my data. The token were generated with the help of childrens count in firebase database. The problem I faced was if two users book their appointment at same time then both the users get same token number. For example, the number of childrens in firebase was 5. If the users A and B book their appointment then both the users get the token number 6. But the other user C book the appointment(after A and B) get the correct token number 8.

My code:

int ct=1;

public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
        ++ct;
        Log.d("log", "onDataChange: " + dataSnapshot1.child("Appointment").child("artistName").getValue());
    }
}

The variable ct represents the token number.

What was the solution to solve the above problem?

Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98

1 Answers1

0

The token should not be generated based on children count under a node. It will not serve the purpose of identifying a token uniquely in your database.

As far as I could understand your problem, you want to provide a token to the users of your application for an automated appointments to some artists. In this case, I would like to suggest you to take another table in your firebase database which will store all the tokens. Tag the token number along with the artist.

So the final table structure will be something like this.

Appointment
    -- Artists
           -- TokenNumber

Token 
    --TokenNumber

If you are familiar with the relational database, you might consider thinking of your token number as a foreign key of another table which is incremented automatically each time a token is assigned to some appointment.

Hope that helps!

Update

Based on the comment, I have found a nice answer in stackoverflow regarding this. Please have a look at the answer on how to increment a value in Firebase. The key idea is to setting the value from client side with a transactional mode. I am sharing the sample code from the answer referred.

public void incrementCounter() {
    firebase.runTransaction(new Transaction.Handler() {
        @Override
        public Transaction.Result doTransaction(final MutableData currentData) {
            if (currentData.getValue() == null) {
                currentData.setValue(1);
            } else {
                currentData.setValue((Long) currentData.getValue() + 1);
            }

            return Transaction.success(currentData);
        }

        @Override
        public void onComplete(FirebaseError firebaseError, boolean committed, DataSnapshot currentData) {
            if (firebaseError != null) {
                Log.d("Firebase counter increment failed.");
            } else {
                Log.d("Firebase counter increment succeeded.");
            }
        }
    });
}
Reaz Murshed
  • 23,691
  • 13
  • 78
  • 98