Hi I am trying to create an social media type app that has a User class. And I need to retrieve the user data from the Firebase realtime database and store it as private attributes in the class. Currently I have tried this code in my user class:
public class User {
private String uID;
private String name;
private String email;
private DatabaseReference mdatabaseReference;
public User(String givenUiD){
this.uID =givenUiD;
mdatabaseReference= FirebaseDatabase.getInstance().getReference();
mdatabaseReference.child("users").child(givenUiD).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
name=dataSnapshot.child("name").getValue(String.class);
email = dataSnapshot.child("email").getValue(String.class);
Log.d(TAG, "onDataChange: "+name);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
public String getName(){
return this.name;
}
}
And this is the section of code I run in the signInFragment:
currentUser=new User(mAuth.getCurrentUser().getUid());
Log.d(TAG, "onComplete: )"+currentUser.getName());
Toast.makeText(getContext(),"Log in successful.Welcome"+currentUser.getName(),Toast.LENGTH_SHORT).show();
However, the issue is that inside the onDataChange
fuction, the logcat displays the correct 'name
' of the user from the database. However when I try to return the name using the getName()
method, the name shows up as null
. I think the issue is name=dataSnapshot.child("name").getValue(String.class);
doesn't store the value in the name
attribute as I would like it to, but I'm not sure how to resolve this. Am I using dataSnapshots in completely the wrong way? Help would be much appreciated, thankyou.