Firebase中OrderByChild()无法按timestamp排序数据求助
Fixing Firebase Data Sorting by Timestamp (as Node Key)
Hey there! Let's get your Firebase data sorted correctly by that timestamp key you're using. I see a couple of small issues in your current code that are throwing off the order—let's break them down and fix them step by step.
What's Going Wrong in Your Current Code?
- Wrong sorting method: You're using
orderByChild("{pushId}/key"), but this is meant to sort by a child field inside each node, not by the node's own key (which is your timestamp). Since your timestamp is the key of each node under "MainDoor", this approach doesn't target the right value. - Unordered collection: When you cast the snapshot value to a
HashMap, you lose the sorted order entirely—HashMaps don't preserve sequence, so even if Firebase returned sorted data, the HashMap would shuffle it.
The Correct Approach
Since your timestamp is the key of each node, we need to use orderByKey() to sort by those keys, and then iterate through the snapshot's children to keep the order intact.
Here's the revised code:
FirebaseDatabase database = FirebaseDatabase.getInstance(); DatabaseReference myRef = database.getReference("MainDoor"); // Use orderByKey() to sort by the node keys (your timestamps) Query dataOrderedByTimestamp = myRef.orderByKey(); dataOrderedByTimestamp.addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { List<MyListData> sortedDataList = new ArrayList<>(); // Iterate through the sorted children—this preserves Firebase's order for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) { // Parse each child into your MyListData object MyListData item = childSnapshot.getValue(MyListData.class); sortedDataList.add(item); // If you need access to the timestamp key itself, use this: String timestampKey = childSnapshot.getKey(); } // Now sortedDataList holds your data in timestamp order! // Use this list for your UI or processing } @Override public void onCancelled(DatabaseError databaseError) { // Don't forget to handle errors Log.e("FirebaseError", "Failed to retrieve data: " + databaseError.getMessage()); } });
Key Notes to Remember
- Why
orderByKey()works: Firebase sorts node keys lexicographically, which matches numeric order for timestamp strings (as long as all timestamps are the same length, like 13-digit Unix milliseconds—this is standard practice). - Avoid HashMaps for ordered data: Always iterate through
dataSnapshot.getChildren()when you need to keep the sorted order. Any conversion to a HashMap or other unordered collection will discard the sequence Firebase provides. - Double-check your database structure: Make sure the direct children under "MainDoor" are exactly the timestamp-keyed nodes you want to sort. If there's an extra layer in between, you'll need to adjust the reference path.
That should get your data showing up in the correct timestamp order. Let me know if you run into any snags!
内容的提问来源于stack exchange,提问作者Rocky Jems
相关产品推荐
相关产品推荐

