如何在 FirebaseRecyclerAdapter 中使用 orderByChild 或 orderByValue

How to use orderByChild or orderByValue in a FirebaseRecyclerAdapter

我正在寻找一种方法将我的数据分类到 RecyclerView 中。目前我正在为此使用优先级方法,但我知道最好应用 orderByChildorderByValue 方法来实现此目的。我只是找不到如何正确执行此操作。

我的(相关)数据结构如下(螺栓格式):

path /events/{event}/GeneralInfo is GeneralInfo{}
path /events/{event}/instances/{instance} is Instance{}

type GeneralInfo {
    owner : KeyString,
    name : ShortNameString | Null, 
    color : Number | Null,
    description : NoteString | Null,
    shared : Boolean | Null,
    startDate : DateString,
    endDate : DateString, 
    instances: Map<KeyString, Boolean>,
    logoAvailable : Boolean | Null
}

type Instance {
    eventKey : KeyString,
    startDateTime : DateString,
    endDateTime : DateString,
    note : String | Null,
}

type KeyString extends String {
    validate() { this.length > 0 && this.length <= 255 }
}

type DateString extends String {
    validate() { this.length == 12 }
}

type ShortNameString extends String {
    validate() { this.length >= 0 && this.length <= 32 }
}

FirebaseRecyclerAdapter 目前初始化如下:

Query q = getGeneralInfo( eventKey ).child( "instances" ).orderByPriority();

mAdapter = new FirebaseRecyclerAdapter<Boolean, InstanceViewHolder>(Boolean.class, R.layout.instance_card, InstanceViewHolder.class, q) {
    @Override
    protected void populateViewHolder(final InstanceViewHolder viewHolder, Boolean model, final int position) {
       getInstanceByKey(mEventKey, refKey).addListenerForSingleValueEvent(new ValueEventListener() {
          @Override
          public void onDataChange(DataSnapshot dataSnapshot) {
             Instance i = dataSnapshot.getValue(Instance.class);
             ....

请注意,我使用索引键字段(带有布尔值的字段)来检索实际数据。索引字段当前正在排序(使用优先级)。

我想直接对实例进行排序(使事情不那么复杂并且能够删除优先级的使用)。

p.s。尽管看起来数据未规范化,但情况确实如此:/events/{event} 路径从未用于检索数据。这样做只是为了保持一些概览。

如果您已经有 child 具有您想要订购的价值,则不需要优先级。从评论看来,您的优先级与开始日期的值相同。在那种情况下,您也可以按 属性:

订购
Query q = getGeneralInfo( eventKey ).child( "instances" ).orderByChild("startDate");

您需要为实例添加索引:

"instances": {
  ".indexOn": "startDate"
}

更新

显然您正在加载 /events/{event}/GeneralInfo/instances,您将其定义为 instances: Map<KeyString, Boolean>

很明显您要存储一个值,我将其更改为 Map<KeyString, Long>,然后将开始日期的时间戳存储为索引中的值。

然后您可以 load/filter 按正确的顺序 orderByValue()