krsna
krsna

Reputation: 4333

How can I get the values out of onDataChange method?

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: "[email protected]"
         | -- 1: "[email protected]"
         | -- 2: "[email protected]"
         | -- 3: "[email protected]"

Upvotes: 0

Views: 976

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 599131

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 = "[email protected]";
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

Upvotes: 3

Related Questions