0

I'll start to explain my issue using an example, I have 2 root collections named Users and Foods. In Users collection, contains documents with User information such as Name, Image, and Age. In foodsCollection, contains documents with Fields such as Food_name, Ingredients, and Image. Now I want to let the users bookmark foods as user wish.Therefore I create one more collection in a user document named Bookmark and saved the Food document's Id in the Bookmark collection's documents. Now I want to get the only Bookmarked Document using saved food document Ids. I ll write my data structure for further understanding.


 Foods(Collection) ----1ztEzZLkTp5XOZzsoYRL(Feilds--Name,Image,Ingradents,Document_Id)
                 
                  ----4Q6k0MifwEyoLs8rgZbs(Feilds--Name,Image,Ingradents,Document_Id)
                
                  ----870BEaDFMkMWTi4VaXmh(Feilds--Name,Image,Ingradents,Document_Id)
                  [...]

 Users(Collection)----User1(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
                                                              ----RandomId("Bookmarked_Doc_Id" - 870BEaDFMkMWTi4VaXmh)
    
                  ----User2(Document)----Bookmarks(Collection)----RandomId("Bookmarked_Doc_Id" - 1ztEzZLkTp5XOZzsoYRL)
    
                  [...]

Now I want to get the Food collection's document data using Bookmarked_Doc_Id

For example, When User1 clicks bookmark tab, he can see 2 bookmarks with its name,image and ingradents.

How can archive this ?

Edit

 rootRef.collection("Users").document(USER_ID).collection("Bookmarks").get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()){
                    for (DocumentSnapshot document : task.getResult()){
                        if (document.exists()){
                            String getDocuments = document.get("Bookmark_Document_Id").toString();
                            loadBookmarks(getDocuments);
                            Log.d(TAG, "onComplete: "+" "+getDocuments);
                        }
                    }
                }
            }
        });
  private void loadBookmarks(String getDocuments) {
    Query query = FirebaseFirestore.getInstance().collection("Foods").whereEqualTo("Document_Id",getDocuments);
    PagedList.Config config = new PagedList.Config.Builder()
            .setEnablePlaceholders(false)
            .setPrefetchDistance(2)
            .setInitialLoadSizeHint(2)
            .setPageSize(3)
            .build();

    FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
            .setQuery(query, config, FoodItems.class)
            .build();

    food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recyclerView.setAdapter(food_items_recycle_adapter);
    food_items_recycle_adapter.notifyDataSetChanged();
    food_items_recycle_adapter.startListening();
}

This code only shows me the latest added bookmark instead of showing all bookmarks.

Isuru Bandara
  • 310
  • 1
  • 3
  • 14
  • Please edit the question to show the code you've tried that isn't working the way you expect. If you don't know how to get a document using its ID, I suggest starting with the [documentation](https://firebase.google.com/docs/firestore/query-data/get-data). – Doug Stevenson Sep 23 '20 at 17:26
  • @DougStevenson I edited my question. – Isuru Bandara Sep 23 '20 at 17:34
  • @DougStevenson I have an idea like when user hit the bookmark button, I can save whole food document in user's bookmark collection, But if someone has changed the original food document data, User's bookmark document data does not change. – Isuru Bandara Sep 23 '20 at 17:37
  • 1
    You might want to explain the specific problem in more detail in your question. Asking simply "is it possible?" is not a very clear question. It is definitely possible to get a document by its ID. We need to know what is your specific problem with that. – Doug Stevenson Sep 23 '20 at 17:41
  • @DougStevenson I edited the topic, I am trying my best to explain my question. Sorry for my bad explanation – Isuru Bandara Sep 23 '20 at 17:51
  • You just save the bookmarks in the desired subcollection and for retrieving, then get the document ID from the user's bookmark subcollection, and query that in the food collection. Where is the problem coming? – s_o_m_m_y_e_e Sep 23 '20 at 18:04
  • @s_o_m_m_y_e_e It only shows the latest added document instead of showing all bookmark documents. – Isuru Bandara Sep 23 '20 at 18:10
  • That's information that should be added to your question. I suggest reading: https://stackoverflow.com/help/how-to-ask – Doug Stevenson Sep 23 '20 at 18:12
  • @DougStevenson Still can't you understand what im trying to ask ? :( – Isuru Bandara Sep 23 '20 at 18:20
  • I don't see anything going wrong in your code. Can you post the desired and problematic results which you want to show in the app? – s_o_m_m_y_e_e Sep 24 '20 at 02:34
  • @s_o_m_m_y_e_e I need to show all the bookmark documents when the user clicks the bookmark button, But my approche do not show all bookmarks. What i need is, User can go to every food item and bookmark them. When he bookmarks an item, that item id save in the his bookmark collection. Now I'm trying to get the item(or items) which he bookmarked. (Remember- I only saved food document id in his bookmark collection.) – Isuru Bandara Sep 24 '20 at 04:48
  • The issue which could be is that you call the _loadDocument()_ method for each bookmark in which you create the query again which only includes one document. I recommend you to first create an ArrayList of the _document IDs_ and then make the query. But I am not quite sure that you can make a query like this because your query would everytime load just **one result**. You should maintain a data structure in which you add all the document Snapshots. – s_o_m_m_y_e_e Sep 24 '20 at 05:04
  • 1
    If you are facing problems using Firebase UI, you can do the pagination yourself! Refer here : [Firestore Pagination](https://stackoverflow.com/questions/50741958/how-to-paginate-firestore-with-android) – s_o_m_m_y_e_e Sep 24 '20 at 05:30

1 Answers1

0

Finally, I solve my problem and this is what I wanted :)

enter code here  final FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
    if (user!=null){
        String USER_ID = user.getUid();

        rootRef.collection("Users").document(USER_ID).collection("Bookmarks")
                .addSnapshotListener(new EventListener<QuerySnapshot>() {
                    @Override
                    public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) {
                        if (error!=null){
                            Log.w(TAG, "Listen failed.", error);
                            return;
                        }
                        List<String> foodlist = new ArrayList<>();
                        assert value != null;
                        for (QueryDocumentSnapshot doc : value) {
                            if (doc.get("Bookmark_Document_Id") != null) {


                                foodlist.add(doc.getString("Bookmark_Document_Id"));
                                Log.d(TAG, "Food items are: " + foodlist);
                               
                                Query query = rootRef.collection("Recipes").document("Food_Recipe").collection("Powder_Recipe").whereIn("Document_Id",foodlist);
                                PagedList.Config config = new PagedList.Config.Builder()
                                        .setEnablePlaceholders(false)
                                        .setPrefetchDistance(2)
                                        .setInitialLoadSizeHint(2)
                                        .setPageSize(3)
                                        .build();

                                FirestorePagingOptions<FoodItems> options = new FirestorePagingOptions.Builder<FoodItems>()
                                        .setQuery(query, config, FoodItems.class)
                                        .build();

                                food_items_recycle_adapter = new Food_Items_Recycle_Adapter(options, progressIndicator,null);
                                recyclerView.setHasFixedSize(true);
                                recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                                recyclerView.setAdapter(food_items_recycle_adapter);
                                food_items_recycle_adapter.notifyDataSetChanged();
                                food_items_recycle_adapter.startListening();

                            }else {
                                Log.d(TAG, "onEvent: this is nulll");
                            }


                        }
                    }
                });
    }

Thank you @s_o_m_m_y_e_e, you tried to solve my issue. There are should be many ways to archive this, but this is working as I wanted.

Isuru Bandara
  • 310
  • 1
  • 3
  • 14