{
"City" : {
"New York" : {
"City Name" : "New York",
"Place to visit" : {
"Times Square" : {
"Address" : "Somewhere",
"Name" : "Times Square"
},
"Central Park" : {
"Address" : "On America",
"Name" : "Central Park"
}
}
},
"Los Angeles" : {
"City Name" : "Los Angeles",
"Place to visit" : {
"Hollywood" : {
"Address" : "Up There",
"Name" : "Hollywood"
},
"Beach" : {
"Address" : "By the sea",
"Name" : "Beach"
}
}
}
}
}
嗨,我对NoSQL数据库尤其是Firebase有点新鲜。如果我按这样构建我的数据,我怎么能得到“城市名称”是纽约的“访问地点”的名称?
我希望结果(时代广场和中央公园)显示为ListView。我怎样才能做到这一点?
或者有没有更好的方法来重构我的数据,以便我可以更轻松地查询我想要的输出?
答案 0 :(得分:0)
首先,城市应该有一个项目清单(在你的情况下是城市名称"纽约或洛杉矶")。
通过这种方式,您可以更轻松地遍历列表并以最快速有效的方式获取所需的城市,这是因为您将获得内置的方法来遍历。
我还重构了你的json响应,以使其成为对象列表并删除冗余变量
以下是回复
{
"City": [{
"New York": {
"Place to visit": {
"Times Square": {
"Address": "Somewhere",
"Name": "Times Square"
},
"Central Park": {
"Address": "On America",
"Name": "Central Park"
}
}
}
},
{
"Los Angeles": {
"Place to visit": {
"Hollywood": {
"Address": "Up There",
"Name": "Hollywood"
},
"Beach": {
"Address": "By the sea",
"Name": "Beach"
}
}
}
}
]
}
答案 1 :(得分:0)
由于您要在查询中使用的城市名称已经是Firebase数据库中的一个节点,要获取这些名称,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference placeToVisitRef = rootRef.child("City").child("New York").child("Place to visit");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String placeToVisit = ds.getKey();
Log.d("TAG", placeToVisit);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
placeToVisitRef.addListenerForSingleValueEvent(eventListener);
您的输出将是:
Times Square
Central Park
答案 2 :(得分:0)
试试这个,
DatabaseReference ref= FirebaseDatabase.getInstance().getReference();
DatabaseReference refPlace= rootRef.child("City").child("New York").child("Place to visit");
refPlace.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> dataSnapshotsChat = dataSnapshot.child("articleTags").getChildren().iterator();
while (dataSnapshotsChat.hasNext()) {
DataSnapshot dataSnapshotChild = dataSnapshotsChat.next();
// check dataSnapshotChild, here you will get the details under Place to visit
Object name = ds.child("Times Square").getValue(Object.class);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});