Sujan D Stc
Sujan D Stc

Reputation: 27

Sorting firebase database by timestamp under a key

I am new on firebase and while working, everything turns out to be great except for one tiny thing, How can we sort the values by timestamp on firebase database ??

I have data in following order..

Here is how my data are seen on the database

enter image description here

In the image, the random key is posted using

 Map<Object, Object> map = new HashMap<Object, Object>();
            map.put("message", messageText);
            map.put("user", UserDetails.username);
            map.put("color", "red");
            map.put("avatar", "1.png");
            map.put("timestamp", ServerValue.TIMESTAMP);
            ref.push().setValue(map);

Now the problem is, I want to retrive data in ascending or descending order (Doesn't matter how). It should come in sequence based on the timeline they were posted/pushed.

I retrive data as following

another.orderByChild("timestamp").limitToLast(10).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            String pw = dataSnapshot.getValue().toString().trim();
            process(pw);toast(pw);
        } else {
            gost("Conversation not started previously.");
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
    }
});

Now when Toast displays data, its jumbled with no sequence. How can I sort the data based on timeline value?

Upvotes: 0

Views: 3886

Answers (1)

Frank van Puffelen
Frank van Puffelen

Reputation: 600006

When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

You need to take care of that list inside your onDataChange method by looping over dataSnapshot.getChildren():

another.orderByChild("timestamp").limitToLast(10).addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        if (dataSnapshot.exists()) {
            for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
                String pw = childSnapshot.getValue().toString().trim();
                process(pw);toast(pw);
            }
        } else {
            gost("Conversation not started previously.");
        }
    }
    @Override
    public void onCancelled(DatabaseError databaseError) {
        throw databaseError.toException(); // don't ignore errors
    }
});

Upvotes: 2

Related Questions