-2

Im checking if an username is repeated or not in my firebase database, when username exists, the value of usernameExist inside the method onDataChanged() would be true, but when I try to access, to the same variable outside the method onDataChanged(), ever the value is false.

 public boolean checkRepeatedUsername(){
        refUsernames = FirebaseDatabase.getInstance().getReference();
        refUsernames.child(username.getEditText().getText().toString().trim());
        refUsernames.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.getValue() != null){
                    usernameExists = true;
                    System.out.println("Exists username? " + " " + usernameExists); //this print true;
                }

            }

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

            }
        });

        System.out.println("Exists? " + " " + usernameExists); //but this ever print false

        if(usernameExists){
            return true;
        }else{
            return false;
        }
}
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
Shean98
  • 13
  • 4
  • Why -3? i think that i wondered something useful and clear... can anyone explain me, why -3? – Shean98 Jul 30 '20 at 19:40
  • Not a downvoter, but this is a common problem folks bump into. Search is your friend in cases such as this: https://stackoverflow.com/search?q=%5Bfirebase-realtime-database%5D%5Bandroid%5D+outside – Frank van Puffelen Jul 30 '20 at 23:44

1 Answers1

0

addListenerForSingleValueEvent is asynchronous and returns immediately, before any data is available. The provided callback will be invoked whenever data becomes available.

Since addListenerForSingleValueEvent returns immediately, your line of code that prints usernameExists is always going to print its initial value.

You can only use the data in the snapshot when it becomes available in the callback. You can't use it synchronously as you are now - you will have to rewrite your code to accept the asynchronous behavior.

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • Okay, so... i need to avoid addListenerForSingleValueEvent methods, and another listener method, right? and do it without any of this methods – Shean98 Jul 30 '20 at 19:43
  • All Firebase APIs are asynchronous. You will need to adopt asynchronous programming practices in order to write your app effectively. – Doug Stevenson Jul 30 '20 at 20:11