0

Database looks like this:

I'm trying to get mail by username, so far I tried:

The storageContainer way by defining string variable on MainActivity class and using storageContainer Function in onDataChange function.

public void storageContainer(String mail){
    this.userMail = mail;
}

This is the getMailByUsername function:

public void getMailByUsername(String username){
    String user_mail;
    mDatabase.child("Users").child(username).child("email").addListenerForSingleValueEvent(new ValueEventListener() {
        String userMail;
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            userMail = dataSnapshot.getValue().toString();
            storageContainer(userMail);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

}
KENdi
  • 7,576
  • 2
  • 16
  • 31
  • What exactly is your problem? – Ziya ERKOC Jul 12 '17 at 18:34
  • Im trying to get dataSnapshot.getValue().toString() out of onDataChange function :/ but i guess i can't ... im trying to get user mail from that database and use it in logIn(String email,String password) function – Greg Paul Jul 12 '17 at 18:36

1 Answers1

4

To solve this, move the declaration of String user_mail inside the onDataChange() method, otherwise it will be null. This is happening due the asynchronous behaviour of onDataChange() method, which is called before even your storageContainer() is called.

Moving the declaration inside the method, solves your problem. Use also a log statement inside the method like this:

Log("TAG", userMail);

If you want to use the value of that String outside that method, please take a look at my answer from this post.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193