I am trying to read a node in my database and return the value retrieved in a single method. When i run the code the data is logged on the console but the method returns a null value.
What i Know:
I know that Firebase retrieves/synchronizes with the database automatically in the background therefore the code inside onDataChanged is executed last.
What i don't know:
How to get my method to return the value gotten from the onDataChanged method.
My code:
public static String telephone;
public static String getMyNumber(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference r = FirebaseDatabase.getInstance().getReference().child("users").child(user.getUid()).child("phone");
r.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
telephone = dataSnapshot.getValue(String.class);
Log.d("YourTag", telephone);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return telephone;
}