Search code examples
javaandroidfirebase-realtime-databaseinstance-variablesanonymous-class

How to change instance variables inside anonymous class


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;
    }
}

Solution

  • 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:

    • you call getUserName before onDataChange,
    • or your onDataChange method does not set the value because it does not go into the if statement or that your dataSnapshot.getChildren() is empty,
    • or even that the userName of the user in the last child is an empty String (Note that your code always returns the userName on the last child, is that inteded?)