0

I want the children count in firebase to assign token. So I was used getChildren() method. This method gives the count and the count was incremented and assigned to each member. The problem raised when two users uses the application at a same time. For example, the children count was 10. If both the users uses the app at same time then both users get count of 10 and it increments gives 11. Hence both the users get token 11. If other user who was use the app after the above two, gets the correct number as 12 and it increments to 13 and 13 was assigned to that user.

 databaseArtists.orderByChild("artistName").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {


                for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {

                    ++ct;
                    Log.d("log", "onDataChange: " + dataSnapshot1.child("Appointment").child(bdate).child(session).child(docname).child("artistName").getValue());

                }
});

Is there anyway to solve my problem?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • can you please highlight the reason why you need to use such a token? – balsick Apr 09 '18 at 17:32
  • I am developing project of token generation for patients in appointment booking. That's why i want token number. – Buvana Megan Apr 10 '18 at 05:01
  • 1
    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 Apr 10 '18 at 07:26
  • In order to solve this, you need to use [Firebase Transactions](https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions). Please see the duplicate. – Alex Mamo Apr 10 '18 at 07:28
  • isn't my answer good enough for you @BuvanaMegan ? – balsick Apr 11 '18 at 11:21
  • Sorry for the late reply! Both of your answers wont work for me. – Buvana Megan Apr 14 '18 at 19:18
  • I want token number uniquely for each patients. If I use transaction then it works single variable(like save users score example). This transaction wont work for every patients – Buvana Megan Apr 14 '18 at 19:20

1 Answers1

0

You need to have a progressive number constantly growing on user demand, and you have to make your users modify concurrently. Firebase offers transactions to solve problems like this.

You will have a structure like this:

{
...
"tokenGenerator": {
    "current": 0
}
...
"users": {
    "userA": {
        ...
        "token": 3
    }
}

When you need to assign a token to a user, e.g. userA the user's client will run a transaction on $.tokenGenerator.token increasing its value and setting it to $.users.userA.token.

balsick
  • 1,099
  • 1
  • 10
  • 23