1

I am trying to retrieve data from the firebase realtime database and save it to a variable like this:

mUserDatabase.child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                myPublicKeyString = dataSnapshot.child("public_key").getValue().toString();
                myPrivateKeyString = dataSnapshot.child("private_key").getValue().toString();

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

Where myPublicKeyString and myPrivateKeyString are global variables. When I try to do a System.out.println(myPublicKeyString); inside the ValueEventListener function it does indeed print out the correct data but when I try to do the same outside of the function it prints out null.

ZeppRock
  • 988
  • 1
  • 10
  • 22
  • 1
    Possible duplicate of [can't get values out of ondatachange method](https://stackoverflow.com/questions/38456650/cant-get-values-out-of-ondatachange-method) – Peter Haddad Apr 04 '18 at 17:14
  • Also check this: https://stackoverflow.com/questions/41407194/value-of-a-global-variable-is-reset-after-it-is-initialised-in-valueeventlistene/41409942#41409942 – Peter Haddad Apr 04 '18 at 17:15
  • check the links above to understand why this happens – Peter Haddad Apr 04 '18 at 17:15
  • Possible duplicate of [How to return dataSnapshot value as a result of a method?](https://stackoverflow.com/questions/47847694/how-to-return-datasnapshot-value-as-a-result-of-a-method) – Alex Mamo Apr 04 '18 at 17:59
  • See the last part of the duplicate to see how you can use that value outside the `onDataChange()` using a custom callback. – Alex Mamo Apr 04 '18 at 18:00

0 Answers0