newbieCoder.pkg
newbieCoder.pkg

Reputation: 277

Populate a RecyclerView with Images from a Firestore collection

I know how to do it in Firebase Real-Time database but since I'm trying to only implement the Firestore, I reached a dilemma.

The question is this: Is there a way to do this in Firestore?

 final ArrayList<Photo> photos = new ArrayList<>();

  DatabaseReference reference = 
  FirebaseDatabase.getInstance().getReference();
  Query query = reference
            .child("user_photos")
            .child(userID);

  query.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for ( DataSnapshot singleSnapshot :  dataSnapshot.getChildren()){
                photos.add(singleSnapshot.getValue(Photo.class));
   }

Upvotes: 1

Views: 425

Answers (1)

Alex Mamo
Alex Mamo

Reputation: 138824

Yes there is. Assuming that you have a database structure in Firestore that looks like this:

Firestore-root
    |
    --- user_photos (collection)
           |
           --- userID (document)
                 |
                 --- //document details

The code to get all the documents within user_photos collection should look like this:

FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference userPhotoRef = rootRef.collection("user_photos");
userPhotoRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            List<Photo> list = new ArrayList<>();
            for (DocumentSnapshot document : task.getResult()) {
                Log.d(TAG, document.getId() + " => " + document.getData());

                if (document.exists()) {
                    Photo photo = document.toObject(Photo.class);
                    list.add(photo); //Add Photo object to the list
                }

                //Do what you need to do with your list
            }
        } else {
            Log.d(TAG, "Error getting documents: ", task.getException());
        }
    }
});

See here more informations regarding getting data from Cloud Firestore.

Upvotes: 3

Related Questions