我想做的是按id排序数据。我知道我应该使用booksInstance.orderByChild(“id”)。我试过这样做,没有任何改变,因为我不知道我应该在代码中使用它。这是我如何显示数据。
private void getData(){
firebaseDatabaseInstance = FirebaseDatabase.getInstance();
// get reference to 'users' node
booksInstance = firebaseDatabaseInstance.getReference("a3lamAlda3wa");
books.clear();
books.addAll(db.getAllA3());
adapter = new BookGridAdapter(this, books);
gridView.setAdapter(adapter);
if (books.isEmpty()) {
Constants.showLoadingDialog(this);
}
booksInstance.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
storeData(dataSnapshot);
}
@Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
BookData book = new BookData(
(String) dataSnapshot.child("id").getValue(),
(String) dataSnapshot.child("book_name").getValue(),
(String)dataSnapshot.child("book_path").getValue(),
(String)dataSnapshot.child("book_path2").getValue(),
"",
(String)dataSnapshot.child("image_path").getValue(),
(String)dataSnapshot.child("image_path2").getValue(),
""
);
db.insertA3(book);
reloadData();
}
});
}
private void storeData(DataSnapshot snapshot) {
books.clear();
for (DataSnapshot alert: snapshot.getChildren()) {
BookData book = new BookData(
(String)alert.child("id").getValue(),
(String)alert.child("book_name").getValue(),
(String)alert.child("book_path").getValue(),
(String)alert.child("book_path2").getValue(),
"",
(String)alert.child("image_path").getValue(),
(String)alert.child("image_path2").getValue(),
""
);
db.insertBook(book);
}
books.addAll(db.getAllBook());
adapter.notifyDataSetChanged();
}
这就是我的数据库的样子
"books" : [ null, {
"book_name" : "book 1",
"book_path" : "gs://appspot.com/books/1.pdf",
"book_path2" : "https://firebasestorage.googleapis.com",
"id" : "a-1",
"image_path" : "gs://mostsharabdallah-c0c65.appspot.com",
"image_path2" : "https://firebasestorage.googleapis.com"
}
答案 0 :(得分:0)
不是将侦听器附加到书籍的位置,而是将其附加到有序查询。所以:
booksInstance.orderByChild("id").addChildEventListener(new ChildEventListener() {
出于好奇:由于您的图书已经有ID,为什么不简单地将它们作为密钥存放在他们的ID下?