0

I wrote a simple method to draw some data from my firebase database:

HashMap curUserInfo;
public void drawUserDataFromDB(String childName) {
        myDB.child(childName).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                System.out.println(dataSnapshot.getValue());
                curUserInfo = (HashMap) dataSnapshot.getValue();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

Then when running

drawUserDataFromDB("123");
System.out.println(curUserInfo);

The System.out.println(dataSnapshot.getValue()); statement prints the correct user info, in HashMap format, while the second print statement prints null

I later tried to change the method slightly to see if the HashMap cast was the issue, and changed it to

public HashMap drawUserDataFromDB(String childName) {
        final HashMap[] hashthing = {new HashMap()}
        myDB.child(childName).addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                hashthing[0] = (HashMap) dataSnapshot.getValue();
                System.out.println(hashthing[0]);

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
        return hashthing[0];
    }

Then

System.out.println(drawUserDataFromDB("123"))

The statement above successfully printed the first hasthing[0] but then again printed null for the returned value

Why is this? Is this some bug? Is there some way to fix it?

Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
M. Chak
  • 530
  • 3
  • 13
  • addListenerForSingleValueEvent is asynchronous and always returns immediately, before the database query is finished. Your callback will be invoked some time later with the results. Put logging statements in your code to observe for yourself. – Doug Stevenson Jun 17 '20 at 18:08
  • See https://stackoverflow.com/questions/50434836/getcontactsfromfirebase-method-return-an-empty-list/50435519#50435519 and many others for a longer explanation and example. – Frank van Puffelen Jun 17 '20 at 18:12

0 Answers0