Reputation: 1
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) {
}
});
}
Upvotes: 0
Views: 914
Reputation: 1
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.
Upvotes: 4