Firebase Firestore订单因无法正常工作 [英] Firebase Firestore order by not working
问题描述
我正在通过官方文档了解有关Firebase Firestore的信息.我正在尝试下面的代码.通知是使用firestore的add()方法添加的.
I am learning about Firebase Firestore through official documentation. I was trying following code. Notifications are added using add() method of firestore.
FirebaseFirestore.getInstance().colRefNotifications()
.orderBy("timestamp", Query.Direction.DESCENDING)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()){
listNotifications.clear();
recyclerViewNotification.removeAllViews();
for (DocumentSnapshot data : documentSnapshots){
Notification notification = data.toObject(Notification.class);
listNotifications.add(notification);
}
notificationGeneralAdapter.notifyDataSetChanged();
}
}
});
Notification.java
private String text;
private String key;
private Date timestamp;
public Notification() {
}
public Notification(String text, String key, Date timestamp) {
this.text = text;
this.key = key;
this.timestamp = timestamp;
}
public String getText() {
return text;
}
public String getKey() {
return key;
}
public Date getTimestamp() {
return timestamp;
}
Firestore
我正在按时间戳降序排列通知.但是,如下面的快照所示,它没有显示所需的输出.
I am ordering notifications by timestamp in descending direction. But, as you can see in the following snapshot, it is not showing desired output.
我做错了什么?谢谢您的帮助.
What am I doing wrong? Thank you for your help.
推荐答案
这是由于嵌套查询而发生的.如果将查询放入侦听器中(成功/失败/完成),orderBy方法将不起作用.将您的下一个查询放入RecyclerView适配器的onBindViewHolder中.
This is happening because of nested queries. If you put a query inside a listener (success/failure/complete), orderBy method will not work. Place your next query inside onBindViewHolder of the RecyclerView adapter.
FirebaseFirestore.getInstance().colRefNotifications()
.orderBy("timestamp", Query.Direction.DESCENDING)
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()){
....
/**If you are nesting queries like this, move second query to**/
/**onBindViewHolder of the RecyclerView adapter**/
FirebaseFirestore.getInstance().colRefUsers()
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
@Override
public void onSuccess(QuerySnapshot documentSnapshots) {
if (!documentSnapshots.isEmpty()){
....
}
}
});
}
}
});
这篇关于Firebase Firestore订单因无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!