I have a class UserName
which has been created for the purpose of returning the userName when provided with userID. The problem is that I can't change the instance variable userName
inside the anonymous class ValueEventListener
. The Log.i()
function inside the anonymous class successfully prints the correct userName but while returning the variable through getUserName()
function it returns empty string variable. How can I change such instance variables inside any anonymous classes ?
public class UserName {
String userName;
public UserName(String userID){
DatabaseReference dbRefUsers = FirebaseDatabase.getInstance().getReference("Users");
Query queryGetUserName = dbRefUsers.orderByChild("userID").equalTo(userID);
queryGetUserName.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot dataSnapshotCurrent: dataSnapshot.getChildren()){
User userCurrent = dataSnapshotCurrent.getValue(User.class);
userName = userCurrent.getName();
Log.i("userName",userName);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
public String getUserName() {
return userName;
}
}