Setting a variable inside onDataChange in Firebase (SingleValue Listener)

This is an example of my code. Right now, if I print the userName variable inside onDataChange, it works fine. But if I try to print the username outside, after the listener, it will print "null". How can I store a variable with the data I want inside onDataChange ()?

public class FireBaseTest extends .... {

    String userName;

    ...

    mDatabase.child("Users").child(key).addListenerForSingleValueEvent(
                    new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                            // Get user value
                            userName = dataSnapshot.child("userName").getValue(String.class);
                            System.out.println(userName); //Not null
                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {
                        }
                    });


    ...

    System.out.println(userName); //Null

EDIT / UPDATE: Therefore, before I had a process that would take on the value that they were listening to and do something with it. I just made some changes to this process and added it to the onDataChanged method to end my suffering. Although this is not entirely satisfactory, it worked. Thanks to all who responded.

+4
3

Firebase , ​​. , .

firebase .

public void doSomething(@NotNull final Callback callback) {

    final Query query = mDatabase.child(FirebaseConstants.TARGET);

    query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            String userName = dataSnapshot.child("userName").getValue(String.class);
            callback.OnComplete(userName);
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}
+3

Firebase Asynchrounosly, , , ValueEventListener, onDataChanged onCancelled.

, userName , , .

, , .

+2

, Firebase. , , , , Firebase, :

1) onDataChange.

2) / addListenerForSingleValueEvent onDataChange.

+1

Source: https://habr.com/ru/post/1652886/


All Articles