这是我的数据库参考:
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = (DatabaseReference) firebaseDatabase.getReference().child("Notifications").orderByChild("Date");
这是我的Firebase控制台的快照:
答案 0 :(得分:0)
您可以按以下方式检索最近的数据:
List<Notifications> notificationList = new ArrayList();
firebaseDatabase = FirebaseDatabase.getInstance();
myRef = (DatabaseReference) firebaseDatabase.getReference().child("Notifications").orderByKey();
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Notifications notification = snapshot.getValue(Notifications.class);
notificationList.add(0,notification);
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
使用firebase,您应该执行一些查询逻辑客户端。降序和升序在Firebase上不可用。
答案 1 :(得分:0)
这是我从Firebase检索数据的方法:
1)制定帮助方法以附加和分离监听器。每当您的实时数据库发生更改时,就会调用此代码。
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mNotificationsDatabaseReference;
private ChildEventListener mChildEventListener;
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Notification currentNotification= dataSnapshot.getValue(Notification.class); //deserialize data (make it an object again)
mNotificationAdapter.add(currentNotification);
//Store your data here in what order you like.
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
public void onCancelled(DatabaseError databaseError) {
}
};
mNotificationsDatabaseReference.addChildEventListener(mChildEventListener);
}
}
private void detachDatabaseReadListener() {
if (mChildEventListener != null) {
mNotificationsDatabaseReference.removeEventListener(mChildEventListener);
mChildEventListener = null;
}
}
2)不要忘记在onResume和onPause上附加和分离侦听器。
@Override
protected void onResume() {
super.onResume();
attachDatabaseReadListener();
}
@Override
protected void onPause() {
super.onPause();
mNotificationAdapter.clear(); //Delete data in adapter which populates a listview. Otherwise you will end up with double items.
detachDatabaseReadListener();
}
有关其他信息和帮助,请阅读official documentation
如果您真的想了解Firebase的基础知识,我建议您看看这个令人惊叹的tutorial(由Google制造)。