gpt4 book ai didi

java - 如何使用 Firestore 对象填充数组

转载 作者:行者123 更新时间:2023-11-29 23:46:13 25 4
gpt4 key购买 nike

我正在尝试使用 Firebase 和 Firestore 制作电子书应用程序。这是数据库的样子:

books
Book1
-title:abc
-category:123
-description:123
Book2
-title:xyz
-category:456
-description:123

所以基本上我需要从 Firebase-firestore 检索数据并将它们放在一个数组中(我称他为 lstBook),所以这是我尝试过但没有成功的代码(MainActivity 中没有显示任何内容)

List<book> lstBook;

private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference notebookRef = db.collection("books");


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstBook = new ArrayList<>();

    @Override
protected void onStart() {
super.onStart();
notebookRef.addSnapshotListener(MainActivity.this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null){
return;
}

for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){
BookActivity note = documentSnapshot.toObject(BookActivity.class);

String title = note.getTvtitle();
String description = note.getTvdescription().toString();

}
lstBook.add(new book(title,"test","",R.drawable.themartian));
}
});
}

我正在使用 cardView 和 RecyclerView 但我基本上可以通过添加此代码(手动)添加书籍

lstBook.add(new book("Book Title","Category","Description",Image here));

最佳答案

试试这个:-

@Override
protected void onStart() {
super.onStart();
notebookRef.addSnapshotListener(MainActivity.this, new EventListener<QuerySnapshot>() {
@Override
public void onEvent(QuerySnapshot queryDocumentSnapshots, FirebaseFirestoreException e) {
if (e != null){
return;
}

for (QueryDocumentSnapshot documentSnapshot : queryDocumentSnapshots){

String title = documentSnapshot.get("tvtitle").toString();
String description = documentSnapshot.get("tvcategory").toString();

lstBook.add(new book(title,"test",description,R.drawable.themartian));

}
}
});
}

关于java - 如何使用 Firestore 对象填充数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51368732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com