问题
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