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;
}
}
The code should work, if you call getUserName
AFTER you call your onDataChange
method.
Here is an example illustrating that it works using a JButton
and an ActionListener
public class UserName {
private String userName;
private JButton button = new JButton();
public UserName() {
button.addActionListener(e -> userName = "bob");
}
public String getUserName() {
return userName;
}
}
If I do
UserName userName = new UserName();
System.out.println(userName.getUserName());
It prints null.
But if I do
UserName userName = new UserName();
userName.getButton().doClick();
System.out.println(userName.getUserName());
Then it prints "bob"
So your issue can be that:
getUserName
before onDataChange
, onDataChange
method does not set the value because it does not go into the if
statement or that your dataSnapshot.getChildren()
is empty,