简体   繁体   中英

Trying to retrieve value from Firebase, but getting null?

As you can see from the code below, I output retrievedValue from inside onDataChange() which works as intended. But I can't output retrievedValue from another place because it returns null .

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        retrievedValue = (Long) dataSnapshot.getValue();

        System.out.println(retrievedValue); //this line works
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

System.out.println(retrievedValue); //this line returns null! How can I fix this?

this line returns null! How can I fix this?

I don't think you understand how asynchronous code works... First, nothing is returned null. Nothing has been assigned yet.

Your code is the exact same as this.

DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
System.out.println(retrievedValue); //this line returns null! 

ref.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {

        retrievedValue = (Long) dataSnapshot.getValue();

        System.out.println(retrievedValue); //this line works
    }

    @Override
    public void onCancelled(DatabaseError databaseError) {

    }
});

There is nothing to fix because you are using Firebase wrong.

If you need retrievedValue , then you should put all related code into (or after, like via another method) onDataChange

For example

private Long retreivedValue; // starts as null

public static void updateSomething(Long data) {
    System.out.println(data); // this line works
}

public static void main(String... args) {
    DatabaseReference ref = FirebaseDatabase.getInstance().getReference();

    ref.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            retrievedValue = (Long) dataSnapshot.getValue();

            updateSomething(retrievedValue); 
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM