0

I wanted to compare the user's email who signed in to my app with already registered user's email from my firebase database.

How can I get the value of emailFromDatabase values outside the onDataChange method so that I could compare the database's email value to my signed in user's email?

usersListDatabaseReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot emailSnapshot: dataSnapshot.getChildren()) {
      String emailFromDatabase = (String) emailSnapshot.getValue();
    }
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {}
});

This is the database structure in my Firebase console.

amapp-731b2addclose
   + messages
   + version
   - userslist
      - email
         |
         | -- 0: "abc@gmail.com"
         | -- 1: "xyz@gmail.com"
         | -- 2: "ghi@gmail.com"
         | -- 3: "mno@gmail.com"
coderpc
  • 4,119
  • 6
  • 51
  • 93

1 Answers1

3

You can't get the value out of the callback. Well... technically you can get it out, but you can't know when that happens.

Instead what you should do is move the code that does the comparison into the onDataChange() callback. E.g.

final String emailFromUser = "pc@somedomain.com";
usersListDatabaseReference.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    for (DataSnapshot emailSnapshot: dataSnapshot.getChildren()) {
      String emailFromDatabase = emailSnapshot.getValue(String.class);
      if (emailFromDatabase.equals(emailFromUser)) {
        System.out.println("Found a matching email");
      }
    }
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {
    throw databaseError.toException(); // don't ignore errors
  }
});

To make the code more reusable, you can create a custom callback interface. For more on that, see getContactsFromFirebase() method return an empty list

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Please see my answer here where you can use the value from datasnapshot outside onDataChange https://stackoverflow.com/a/55741593/3904109 – DragonFire Apr 18 '19 at 08:17