vendredi 10 août 2018

If Equal to String Doesn't Work in Firestore Snapshot Listener

Building an Android chat app using Firebase Firestore database.

I wanted to check if a message in the database was sent by the current user, or another user. This way, I can display the chat bubbles right or left accordingly. However, I'm not able to compare as the comparison always returns "NOT TRUE", although I can't understand why. Check it out:

I'm comparing the userID with the sender's userID that I store in Firestore. They print out the same in the log. But when I compare them in an if-statement. It says they're not equal.

public void getLiveChatMessages(final ArrayList<ChatConversationMessage> messageArrayList) {
    db.collection("users")
            .document(userID)
            .collection("conversations")
            .document("conversation0") //Specified conversation
            .collection("messages")
            .addSnapshotListener(new EventListener<QuerySnapshot>() {
                @Override
                public void onEvent(@Nullable QuerySnapshot value,
                                    @Nullable FirebaseFirestoreException e) {
                    if (e != null) {
                        Log.w(TAG, "Listen failed.", e);
                        return;
                    }

                    for (QueryDocumentSnapshot doc : value) {
                        if (doc.get("message") != null) {
                            String messageSender = doc.getString("From user with ID");

                            if (messageSender == userID){
                                Log.e(TAG, "the messageSender IS equal to the userID");
                                Log.e(TAG, "the messageSender: " + messageSender);
                                Log.e(TAG, "the userID: " + userID);
                            } else {
                                Log.e(TAG, "the messageSender is NOT equal to the userID");
                                Log.e(TAG, "the messageSender: " + messageSender);
                                Log.e(TAG, "the userID: " + userID);
                            }
                        }
                    Log.d(TAG, "Message: " + messageArrayList);
                    }
                 }
            });
}

and here is my Log output:

E/chat: the messageSender is NOT equal to the userID

the messageSender: ypiXrobQxuZ0wplN5KO8gJR7Z4x2

the userID: ypiXrobQxuZ0wplN5KO8gJR7Z4x2

how can they not be equal???

Aucun commentaire:

Enregistrer un commentaire