简体   繁体   English

如何将键和值从Firebase数据库放入哈希图?

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

I have this list of dataSnapshot from database 我有数据库中的dataSnapshot列表

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. 现在,我的问题是我无法在personTypetoDisplayMap和displayToPersonTypeMap中存储任何数据。 Everytime I debug the app, its size are always size=0. 每次调试应用程序时,其大小始终为size = 0。

I also tried doing personTypeToDisplayMap.put("string", "sassy"); 我也尝试做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. 换句话说,您不能简单地在onDataChange()方法外部使用personTypeToDisplayMapdisplayToPersonTypeMap映射,因为由于此方法的异步行为,该映射始终zero 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. 一个快速的解决这个问题是使用两个地图只内onDataChange()方法,否则我建议你看我anwser从这个最后部分职位中,我已经解释了如何可以使用自定义的回调来完成。 You can also take a look at this video for a better understanding. 您也可以观看此视频 ,以更好地理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM