如何使用Firestore对象填充数组

时间:2018-07-16 19:17:35

标签: java android arrays firebase google-cloud-firestore

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

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

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

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));

1 个答案:

答案 0 :(得分:0)

尝试一下:-

@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));

            }
        }
    });
}