Android 中的 Firebase 数据描述排序 [英] Firebase Data Desc Sorting in Android

查看:34
本文介绍了Android 中的 Firebase 数据描述排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据存储在 Firebase 存储中.

I am storing data in Firebase storage.

对象 Comment 带有属性 timestamp.当我将数据从设备推送到 Firebase 时,我使用 currentTime 填充 timestamp 并存储在 long 数据类型中.

Object Comment with attribute timestamp. When I push data from device to Firebase I'm populating timestamp with currentTime and store in long data type.

当我使用 firebaseRef.orderByChild("timestamp").limitToLast(15) 检索数据时,结果未按我预期的方式排序.

When I do retrieving the data with firebaseRef.orderByChild("timestamp").limitToLast(15) result is not sorting how I expected.

我什至玩弄规则但没有结果:

I even played around with rules and no result:

{
    "rules": {
        ".read": true,
        ".write": true,
        ".indexOn": "streetrate",
        "streetrate": {
          ".indexOn": ".value"
        }
    }
}

我尝试将 timestamp 存储在 String 数据类型中,同样的问题.

I tried store timestamp in String data type, same issue.

推荐答案

Firebase 可以按给定的属性按升序排列项目,然后返回前 N 个项目 (limitToFirst()) 或最后 N 个项目 (limitToLast()).没有办法表明您想要按降序排列的项目.

Firebase can order the items in ascending order by a given property and then returns either the first N items (limitToFirst()) or the last N items (limitToLast()). There is no way to indicate that you want the items in descending order.

有两个选项可以获得您想要的行为:

There are two options to get the behavior you want:

  1. 使用 Firebase 查询获取正确的数据,然后在客户端对其重新排序

  1. Use a Firebase query to get the correct data, then re-order it client-side

向数据中添加具有降序值的字段

Add a field that has a descending value to the data

对于后一种方法,通常使用反向时间戳.

For the latter approach, it is common to have a inverted timestamp.

-1 * new Date().getTime();

这篇关于Android 中的 Firebase 数据描述排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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