How to query a document field inside of queryDocumentSnapshot Firestore

Ethan :

I am building a chatroom application and am trying to query all messages then separate them accordingly based on the message sender.

This is what my Firestore architecture looks like:

enter image description here

And my code so far:

 CollectionReference chatRoomMsgs = db.collection("chatrooms").document(chatRoomID).collection("Messages");
    chatRoomMsgs.get()
            .addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
                @Override
                public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
                    for(QueryDocumentSnapshot documentSnapshot: queryDocumentSnapshots){
                        if(documentSnapshot.get("sentby") == firebaseUser.getUid()){

                        }
                    }
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {

                }
            });

What I am (currently) trying to do is pull ALL chatroom messages first, and then separate them out in onSuccess.

I am trying to say "ok if the message was sent by this user, grab the image field value of that same document and add it to an array so the image can be accessed later, and if the message was not sent by the same user, also grab the image url but add it to a different array"

How can I do this? Thanks!

Update I tried adding the while loop below to get some sort of output, wasn't triggering

ArrayList<String> sentPics = new ArrayList<String>();      
while(documentSnapshot.get("sentby") == firebaseUser.getUid()){
                                    sentPics.add(documentSnapshot.get("image").toString());
                                    Log.d("PICLIST", sentPics.toString());
                                }
Alex Mamo :

If you want to get all the messages sent by a specific user, then you should use the following query:

CollectionReference chatRoomMsgs = db.collection("chatrooms").document(chatRoomID).collection("Messages");
Query sendByQuery = chatRoomMsgs.whereEqualTo("sentby", firebaseUser.getUid());
sendByQuery.addOnSuccessListener(/* ... */);

Using this solution you'll significantly reduce the number of read operations as you get as a result only the messages that correspond to the logged-in user.

Your solution is very expensive because you are getting all messages that exist in the Messages collection and you filter them on the client. If you have a total of 100 messages in the collection but only 10 correspond to the logged-in user, you'll be charged with 100 reads. In my solution, you'll only be charged with 10, as the query only 10 messages returns.

If want to see another approach, here you can find a tutorial on how to create a complete and functional Firestore Chat App.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=350313&siteId=1