如何根据 for upcoming/live 事件从 Firebase 数据库中检索事件

How to retrieve events from Firebase Database based on the for upcoming/live events

我正在开发一种活动组织应用程序。因此,我将事件的开始时间、开始日期、结束时间和结束日期保存在 FirebaseDatabase 中,格式如下:分别为 hh:mm:ssdd-MM-yyyy

我在这个参考下保存:

mDatabase = FirebaseDatabase.getInstance().getReferenceFromUrl("https://example-113be.firebaseio.com/events/")
mDatabase.child(itemID).setValue(events);

其中 itemID 是使用此代码检索的推送密钥:itemID = mDatabase.push().getKey();

问题: 所以,我想做的是尝试根据 startTime 和 startDate 在 2 个类别中过滤数据 - "Live events" 和 "events scheduled for later"。比如如果事件的开始时间小于设备当前时间,则表示事件已经开始,应该显示在"live event"类别下,如果开始时间大于当前时间,则表示事件尚未"t been started yet and should be shown under " ]安排在以后”类别。

我想要的: 就是这样取数据,这样上面描述的问题应该就解决了。请告诉我怎么做。

请告诉我是否需要重组我保存数据的方式,以及我是否需要将其他内容与所有数据一起存储。

不要以字符串格式保存时间和日期。 使用 UNIX 时间戳 格式,因此您可以轻松地以任何您想要的方式进行过滤和排序

但是不要忘记在数据库规则中指定.indexOn

检索所有事件的示例,将在第二天发生

final long now = System.currentTimeMillis();
mDatabase.orderByChild("endTimestamp")
    .startAt(now).endAt(now + DateUtils.DAY_IN_MILLIS)
    .addChildEventListener(...);

.indexOn 是 Firebase 的助手,所以它会知道如何为您的数据编制索引。

{
  "rules": {
    "$eventKey": {
      ".read": "true",
      ".write": "true",
      ".indexOn": "["endTimestamp","startTimestamp"]"
    }
  }
}

我建议您以 Long 纪元格式保存日期和时间。 Epoch explanation in wikipedia. For example : 1471446000000 in human time is 17 Aug 2016 15:00:00 (look at this site 了解转换的工作原理)

有了这个,你只需要数据库结构中的startDateTimeendDateTime。然后你可以做 query.startAt(currentDeviceTimeInEpoch, "startDateTime"); 来获得未来的事件。

对于"live events",我能想到的解决办法是先检索所有事件,然后再做基本选择if (currentTime > startDateTime && currentTime < endDateTime)