简体   繁体   中英

How to put the key and value from firebase database to hashmap?

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

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.

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