0

So I have a root in the database like this:

users {
    "user1" {
          username: "username1",
          email: "email@email.com"
     }
    "user2" {
          ...
     }
     ...
}

Now, I want to register a new user, so for that I need to check if the username that the new user choose is already chosen. For that I created a single time event and gather all usernames in a string list:

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users");
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            List<String> res = new ArrayList<String>();

            Iterable<DataSnapshot> users = dataSnapshot.getChildren();
            for (DataSnapshot user : users) {
                res.add(user.child("username").getValue(String.class));
            }
            // No way to return anything
        }

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

But I have a problem, that method is asynchronous. I need to gather all usernames and know if any exists in that list synchronously.

Is there any way to achieve this?

AL.
  • 36,815
  • 10
  • 142
  • 281
jacosro
  • 509
  • 1
  • 5
  • 21
  • This should help you: https://stackoverflow.com/questions/38689663/firebase-multiple-users-simultaneously-updating-same-object-using-its-old-valu, https://firebase.google.com/docs/database/android/read-and-write#save_data_as_transactions – Markaos Jun 07 '17 at 19:52
  • I don't see how it could help me, the problem is not with the data corruption, but is with that I need all that information on a single time. – jacosro Jun 07 '17 at 19:58
  • OK, did some more "research" and found this: https://stackoverflow.com/questions/18554623/firebase-how-to-prevent-duplicate-entries-atomically - accepted answer suggests setting the unique field as a key so that it won't be possible to insert duplicate – Markaos Jun 07 '17 at 20:06

0 Answers0