-1

I have a utility class in my Android application used to hold functions that are reused throughout the app. One of the functions returns a Map of the current logged in users information. When I call this function from an Activity I get no errors but the Map appears to be empty.

Below is the utility class method

public static Map<String,String> getUserInfo(String uniqueID)
{

    final Map<String, String> currUserInfo = new HashMap<>();

    final DatabaseReference database =
            FirebaseDatabase.getInstance().getReference().child("Users").child(uniqueID);

    database.addValueEventListener(new ValueEventListener()
    {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
        {
            User user = dataSnapshot.getValue(User.class);

            currUserInfo.put("user_firstname",user.getFirstName());
            currUserInfo.put("user_secondname", user.getSecondName());
            currUserInfo.put("user_username", user.getUsername());
            currUserInfo.put("user_profile", user.getProfilePicURL());

                     }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError)
        {
            Log.d(TAG, "onCancelled: " + databaseError.getMessage());
        }
    });

    return currUserInfo;
}

Below is how I am calling the function

        userInfo = Utilities.getUserInfo(userID);

"userInfo" is declared at the top of the activity as this

   private Map<String, String> userInfo;
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
user10431501
  • 153
  • 1
  • 2
  • 15

1 Answers1

4

I'm not an Android developer, but by looking at your code I notice you attach a listener to the DatabaseReference instance. Inside that ValueEventListener you put the extracted values from Firebase.

What might happen is that this listener isn't invoked immediatly, but in an asynchronous manner. This means your getUserInfo method is allowed to return independently of the onDataChange method execution.

This might lead to your Map<String, String> being empty after returning.

LppEdd
  • 20,274
  • 11
  • 84
  • 139