0

I want to make a boolean method which can check if a user's nickname is unique, but I'm faced with a problem.

T have such structure of database:
enter image description here

I have this function:

public boolean isNickUnique(String nickname, DatabaseReference ref){
    final boolean[] res = {true};
    ref = ref.child(nickname);
    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            if(snapshot.exists())
                res[0] = false;
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
    return res[0];}

The OnDataChange method checks the nickname uniqueness successfully, but the isNickUnique method returns the result before the ValueEventListener finishes his work. How can I solve this problem?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807

0 Answers0