Order by date in negative timestamp is not working in Firebase

后端 未结 1 448
鱼传尺愫
鱼传尺愫 2020-12-20 10:22

Query used:

q = FirebaseDatabase.getInstance().getReference().child(\"products\").orderByChild(\"timestamp\");
q.addValueEventListener(new ValueEventListener         


        
相关标签:
1条回答
  • 2020-12-20 10:46

    When you execute a query against the Firebase Database, it returns three pieces of information for each matching node:

    1. the value of that node
    2. the key of that node
    3. the order of that node relative to the other nodes in the result

    When you print the snapshot, you're actually printing a Map<String, Object> of the query result. And in a map there is only space for two pieces of information: the key of each node and the value of that node. So the order of the nodes is lost when you print the result.

    For that reason you should iterate over the children of the result with the built-in getChildren() method of the snapshot:

    public void onDataChange(DataSnapshot dataSnapshot) {
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            Log.d("datasnapshot", child.getKey()+": "+child.getValue());
        }
    }
    

    And with this you will see the children in the order of their timestamp.

    If you want to keep them in a list (so that the order is maintained), I recommend simply keeping a list of snapshots:

    public void onDataChange(DataSnapshot dataSnapshot) {
        List<DataSnapshot> list = new LinkedList<DataSnapshot>();
        for (DataSnapshot child: dataSnapshot.getChildren()) {
            Log.d("datasnapshot", child.getKey()+": "+child.getValue());
            list.add(child);
        }
    }
    
    0 讨论(0)
提交回复
热议问题