问题描述
我遇到了一个奇怪的问题,在这个问题中,使用 orderByChild()
的Firebase查询并不实际排序数据。下面是我试图订购的数据的快照:(为了这个例子,总数是关闭的)$ b
I'm running into a weird issues in which a Firebase query using orderByChild()
doesn't actually order the data. Below is a snapshot of the data that I'm trying to order: (total is off for the sake of this example)
This is the code that I've used so far:
Query query = locationComment.orderByKey();
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
return;
}
data.clear();
adapter.notifyDataSetChanged();
String userId;
String time;
String comment;
Map<String, String> commentMap = (Map) dataSnapshot.getValue();
for (Map.Entry<String, String> entry : commentMap.entrySet()) {
if(!((entry.getKey()).contains("total"))) {
String[] keyString = (entry.getKey()).split(",");
time = keyString[0];
userId = keyString[1];
comment = entry.getValue();
Date resultdate = new Date(Integer.parseInt(time));
data.add(new Comment(comment,
DateFormat.getDateTimeInstance().format(resultdate), userId));
adapter.notifyItemInserted(data.size());
}
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
I'm getting each and every key-value pair (barring total) except that it's not in order as expected (ordered by key). The Firebase docs say that the keys are ordered lexicographically if they can't be parsed into a 32 bit integer.
Either way though the order should be as shown in the image but the data that I get back while looping through the map is not in this order.
I would really appreciate it if someone could point me in the right direction. Thanks!
When you execute a query you get three things:
- they keys
- the values
- the relative order between these
When you convert the result to a Map
it can only hold two of these, so the order is lost. To prevent this, you should use the DataSnapshot.getChildren()
method:
Query query = locationComment.orderByKey();
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
return;
}
data.clear();
for (DataSnapshot child : dataSnapshot.getChildren()) {
...
}
adapter.notifyDataSetChanged();
}
Also see this example in the Firebase documentation on working with lists: https://firebase.google.com/docs/database/android/lists-of-data#listen_for_value_events
这篇关于使用Firebase Android对数据进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!