zakaria khalil
zakaria khalil

Reputation: 13

How to fill an array using Firestore Objects

i am trying to make a e-book Application Using Firebase and Firestore . Here is how the database looks like :

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

so basically i need to retrieve data from Firebase-firestore and put them in an array ( i called him lstBook ) , so here is my code that i have tried but it haven't worked ( Nothing shown at the 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));
        }
    });
}

i am using cardView and RecyclerView but i can add books Basically (Manual) by adding this code

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

Upvotes: 1

Views: 548

Answers (1)

Raj
Raj

Reputation: 3001

Try this:-

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

            }
        }
    });
}

Upvotes: 1

Related Questions