Why I am getting an ArrayList instead a HashMap on Firebase-RealDatabase?

对着背影说爱祢 提交于 2019-12-25 08:34:06

问题


My Database:

    {
    "Shops": {
        "Title": {
            "1": "Footlocker",
            "2": "Nike Store",
            "3": "Adidas Store"
        },
        "Lat": {
            "1": "123",
            "2": "123",
            "3": "123"
        },
        "Lon": {
            "1": "123",
            "2": "123",
            "3": "123"
        }
    }
}

The numbers "1","2" and "3" represent a shop. For example "1" shop has "Footlocker" for title and "123" latitude (probably this should be a number, but that's not my problem).

My goal is to get all the titles in a Hashmap<String,String> (key would be "1"... value "Footlocker" etc...)

So I create a reference to "Title" key in database and add the listener,

DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Shops").child("Title");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                HashMap<String,String> map = (HashMap<String,String>) dataSnapshot.getValue();
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

As you can imagine the above code throws an exception because an ArrayList cannot be cast to a HashMap.

My question is, shouldn't I be getting a HashMap instead with the numbers as keys and the titles as values?


回答1:


You've shown your "database" as a JSON document.

If you parsed that using a JSON parser, sure, you might expect a TreeMap, to be exact, but in Firebase's terms, I think you've confused the "index" of the elements with what you think should be a "key".

So, you get a list, not a Map. No big deal, really. You can still iterate over the elements

If you want a (somewhat) better structure, I would suggest

Stores 
    Footlocker
        Lat
        Lon
    Nike
       ... 
    Adidas
       ... 

Or as Frank comments, use the natural key ordering that Firebase can generate.

Stores 
    <id_0>
        name: "Footlocker"
        Lat: 0.00
        Lon: 0.00
    <id_1>
        name: "Nike"
        ...
    <id_2> 
        name: "Adidas"
        ... 

Additional point. Don't use a HashMap, use objects to represent the data

public class Store {
    String name;
    Double lat, lon;

    public Store() {
        // Required empty-constructor
    }

    // getters & setters...
}


来源:https://stackoverflow.com/questions/42392881/why-i-am-getting-an-arraylist-instead-a-hashmap-on-firebase-realdatabase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!