在密钥下按时间戳对Firebase数据库进行排序 [英] Sorting firebase database by timestamp under a key

查看:54
本文介绍了在密钥下按时间戳对Firebase数据库进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Firebase的新手,在工作时,除了一件很小的事情,一切都变得很棒,我们如何才能在Firebase数据库上按时间戳对值进行排序?

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 ??

我有以下顺序的数据.

这是我的数据在数据库中的显示方式

Here is how my data are seen on the database

在图像中,使用

 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.

我按以下方式检索数据

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) {
    }
});

现在,当 Toast 显示数据时,其杂乱无序.如何根据时间轴值对数据进行排序?

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

推荐答案

对Firebase数据库执行查询时,可能会有多个结果.因此,快照包含这些结果的列表.即使只有一个结果,快照也会包含一个结果的列表.

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.

您需要通过遍历 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
    }
});

这篇关于在密钥下按时间戳对Firebase数据库进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆