1

I have this list of dataSnapshot from database

dataSnapshot:
"DataSnapshot { key = personTypes,
value = {RESIDENT_HOMEOWNER=Resident Homeowner, 
RESIDENT_RELATIVE=Resident Relative,
ADMIN=Admin, DRIVER_OUT=Driver Stay-out} }"

and from data: (database)

data:
"DataSnapshot { key = ADMIN,
value = Admin }"

my code is

private Map<String, String> personTypeToDisplayMap = new HashMap<>();
private Map<String, String> displayToPersonTypeMap = new HashMap<>();

public void fetchPersonTypes() {
    getDbRefKlearyan().child("personTypes").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if(dataSnapshot.hasChildren()) {
                for(DataSnapshot data : dataSnapshot.getChildren()) {
                    personTypeToDisplayMap.put(data.getKey(), data.getValue(String.class));
                    displayToPersonTypeMap.put(data.getValue(String.class), data.getKey());
                }
            }
        }

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

Now, my problem is i cant store any data in personTypetoDisplayMap and displayToPersonTypeMap. Everytime I debug the app, its size are always size=0.

I also tried doing personTypeToDisplayMap.put("string", "sassy"); for testing but the result is the same

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ina Yano
  • 75
  • 2
  • 10
  • 1
    The size for `personTypeToDisplayMap` and `displayToPersonTypeMap` are zero even if you verify this inside the `onDataChange()` method? – Alex Mamo Jun 27 '18 at 12:40
  • @AlexMamo what do you mean by verifying it inside onDataChange()? It's visibly inside the onDataChange method – Ina Yano Jun 27 '18 at 12:47
  • 1
    Check the size of those maps right after the for loops ends. If you are checking there the size is true that it isn't zero, right? – Alex Mamo Jun 27 '18 at 12:50
  • oh okay, thank you! @AlexMamo – Ina Yano Jun 27 '18 at 13:02

1 Answers1

0

You cannot use something now, that hasn't been loaded yet. With other words, you cannot simply use the personTypeToDisplayMap and displayToPersonTypeMap maps outside the onDataChange() method because it will always have the size of zero due the asynchronous behaviour of this method. This means that by the time you are trying to use those maps outside that method, the data hasn't finished loading yet from the database and that's why is not accessible.

A quick solve for this problem would be to use the both maps only inside the onDataChange() method, otherwise I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193