我尝试使用FirebaseUI Recyclerview订购从Firebase获取的列表。排序取决于在客户端中进行的平均计算(计算每个会话的平均评级)。我的数据结构如下所示:
首先,我按天过滤所有sessions
并填充RecyclerView。在实现适配器时,我覆盖了onChildrenChanged
,因此我可以计算每个孩子的平均评分。然后,在计算所有平均值之后,当我打算订购集合时,我覆盖onDataChanged
:
Query query = FirebaseDatabase.getInstance()
.getReference("sessions")
.orderByChild("day")
.equalTo(day);
FirebaseRecyclerOptions<Session> options = new FirebaseRecyclerOptions.Builder<Session>()
.setQuery(query, Session.class)
.setLifecycleOwner(this)
.build();
adapter = new CustomRecyclerViewAdapter(options) {
@Override
public void onChildChanged(ChangeEventType type, DataSnapshot session, int newIndex, int oldIndex) {
super.onChildChanged(type, session, newIndex, oldIndex);
calculateAverageRatingOfSession(session);
}
@Override
public void onDataChanged() {
Collections.sort(getSnapshots(), new Comparator<Talk>() {
@Override
public int compare(Session s1, Session s2) {
return Float.compare(s1.getAverageRating(), s2.getAverageRating());
}
});
}
};
recycler.setAdapter(adapter);
问题是我得到了这个例外:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: cz.devconf2017, PID: 20094
java.lang.UnsupportedOperationException
at java.util.AbstractList.set(AbstractList.java:132)
at java.util.AbstractList$ListItr.set(AbstractList.java:426)
at java.util.Collections.sort(Collections.java:247)
at cz.devconf2017.vote.DayVotingFragment$1.onDataChanged(DayVotingFragment.java:100)
at com.firebase.ui.common.BaseObservableSnapshotArray.notifyOnDataChanged(BaseObservableSnapshotArray.java:163)
at com.firebase.ui.database.FirebaseArray.onDataChange(FirebaseArray.java:108)
at com.google.android.gms.internal.zzduz.zza(Unknown Source)
at com.google.android.gms.internal.zzdwu.zzbvb(Unknown Source)
at com.google.android.gms.internal.zzdxa.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
我认为ObservableSnapshotArray
不可排序,但我想不出有不同的方法。
我如何解决此异常或从客户端排序数据?