CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

Receive Messages

Learn how to receive messages and fetch history & unread messages.

Receiving messages with CometChat has two parts:

  1. Adding a listener to receive real-time messages when your app is running
  2. Calling a method to retrieve missed messages when your app was not running

Real-time Messages

In other words, as a recipient, how do I receive messages when my app is running?

For every activity or fragment you wish to receive messages in, you need to register the MessageListener using the addMessageListener() method.

We suggest adding the listener in the onResume() method of the activity or the fragment where you wish to receive these events in.

private String listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(listenerID, new CometChat.MessageListener() {
  @Override
  public void onTextMessageReceived(TextMessage textMessage) {
    Log.d(TAG, "Text message received successfully: " + textMessage.toString());
  }
  @Override
  public void onMediaMessageReceived(MediaMessage mediaMessage) {
    Log.d(TAG, "Media message received successfully: " + mediaMessage.toString());
  }
@Override
  public void onCustomMessageReceived(CustomMessage customMessage) {
  Log.d(TAG, "Custom message received successfully: " +customMessage.toString());
}
});
val listenerID:String = "UNIQUE_LISTENER_ID"

CometChat.addMessageListener(listenerID,object :CometChat.MessageListener(){

    override fun onTextMessageReceived(message: TextMessage?) {
        Log.d(TAG, "Text message received successfully: " + message?.toString())
    }

    override fun onMediaMessageReceived(message: MediaMessage?) {
        Log.d(TAG, "Media message received successfully: " + message?.toString())
    }
  
  override fun onCustomMessageReceived(message: CustomMessage?) {
    Log.d(TAG, "Custom message received successfully: " + message?.toString())
  }

})

Parameter

Description

listenerID

An ID that uniquely identifies that listener. We recommend using the activity or fragment name

We recommend you remove the listener once the activity or fragment is not in use. Typically, this can be added in the onPause() method.

private String listenerID = "UNIQUE_LISTENER_ID";

CometChat.removeMessageListener(listenerID);
val listenerID:String = "UNIQUE_LISTENER_ID"

CometChat.removeMessageListener(listenerID)

🚧

As a sender, you will not receive your own message in a real-time message event. However, if a user is logged-in using multiple devices, they will receive an event for their own message in other devices.

Missed Messages

In other words, as a recipient, how do I receive messages that I missed when my app was not running?

For most use cases, you will need to add functionality to load missed messages. If you're building an on-demand or live streaming app, you may choose to skip this and fetch the message history (say, last 100 messages) instead.

Using the same MessagesRequest class and the filters provided by the MessagesRequestBuilder class, you can fetch the message that we sent to the logged-in user but were not delivered to them as they were offline. For this, you will require the ID of the last message received. You can either maintain it at your end or use the getLastDeliveredMessageId() method provided by the CometChat class. This ID needs to be passed to the setMessageId() method of the builder class.

Now using the fetchNext() method, you can fetch all the messages that were sent to the user when they were offline.

The code snippet below demonstrates how this can be achieved.

private int limit = 30;
private int latestId = CometChat.getLastDeliveredMessageId();

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setMessageId(latestId).setLimit(limit).build();

messagesRequest.fetchNext(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
var messagesRequest:MessagesRequest?=null
val latestId=CometChat.getLastDeliveredMessageId()
val limit:Int=30
   messagesRequest=MessagesRequest.MessagesRequestBuilder().setMessageId(latestId).setLimit(limit).build()
       messagesRequest?.fetchNext(object:CometChat.CallbackListener<List<BaseMessage>>(){
       override fun onSuccess(p0: List<BaseMessage>?) {
         if (!p0.isNullOrEmpty()) {
            for (baseMessage in p0) {
              if (baseMessage is TextMessage) {
                 Log.d(TAG, "TextMessage: $baseMessage")
               }
              if (baseMessage is MediaMessage) {
                Log.d(TAG, "MediaMessage: $baseMessage")
               }
             }
           }
    }
      override fun onError(p0: CometChatException?) {
        Log.d(TAG, "Message fetching failed with exception: " + p0?.message)
      }
})

Using additional filters you can also fetch the offline messages for a particular user or a group.

Calling the fetchNext() method on the same object repeatedly allows you to fetch all the offline messages for the logged-in user.

Unread Messages

In other words, as a logged-in user, how do I fetch the messages I've not read?

For All One-on-one & Group Conversations

Using the MessagesRequest class described above, you can fetch the unread messages for the logged-in user. In order to achieve this, you need to set the unread variable in the builder to true using the setUnread() method so that only the unread messages are fetched.

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setUnread(true).setLimit(20).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
val messagesRequest = MessagesRequest.MessagesRequestBuilder().setUnread(true).setLimit(20).build()

messagesRequest.fetchPrevious(object : CometChat.CallbackListener<List<BaseMessage>>() {
        override fun onSuccess(list: List<BaseMessage>) {
            for (message in list) {
                if (message is TextMessage) {
                     Log.d(TAG, "Text message received successfully: $message")
                 } else if (message is MediaMessage) {
                     Log.d(TAG, "Media message received successfully: $message")
                 }
              }
           }

        override fun onError(e: CometChatException) {
            Log.d(TAG, "Message fetching failed with exception: " + e.message)
          }
      })

The above snippet will help you fetch the last 20 unread messages for the logged-in user. You can also fetch the unread messages for a particular user or a group by setting the UID and GUID using the setUID() and setGUID() methods respectively.

📘

BaseMessage

The list of messages received is in the form of objects of BaseMessage class. A BaseMessage can either be an object of the TextMessage, MediaMessage, CustomMessage, Action or Call class. You can use the instanceOf operator to check the type of object.

Message History

In other words, as a logged-in user, how do I fetch the complete message history?

For All One-on-one & Group Conversations

Using the same MessagesRequest class discussed above, you can fetch all the messages for a logged-in user which involves their messages for all one-on-one and group conversations. Applying the filters using the MessagesRequestBuilder class, you can fetch messages either before or after a particular message ID or timestamp.

The below code snippet shows how to fetch the last 50 messages for all conversations (one-on-one and groups) the logged-in user is a part of.

private int limit = 50;
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setLimit(limit).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
var messagesRequest:MessagesRequest?=null

val limit:Int=30
   messagesRequest=MessagesRequest.MessagesRequestBuilder().setLimit(limit).build()
       messagesRequest?.fetchPrevious(object:CometChat.CallbackListener<List<BaseMessage>>(){
       override fun onSuccess(p0: List<BaseMessage>?) {
       if (!p0.isNullOrEmpty()) {
          for (baseMessage in p0) {
            if (baseMessage is TextMessage) {
               Log.d(TAG, "TextMessage: $baseMessage")
             }
            if (baseMessage is MediaMessage) {
              Log.d(TAG, "MediaMessage: $baseMessage")
             }
           }
         }
         
}
      override fun onError(p0: CometChatException?) {
      Log.d(TAG, "Message fetching failed with exception: " + p0?.message)
      
      }
})

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch all the previous messages in a paginated way.

For a Particular One-on-one Conversation

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation between the logged-in user and any particular user. For this use case, it is mandatory to set the UID parameter using the setUID() method of the builder. This UID is the unique ID of the user for which the conversation needs to be fetched.

private String UID = "UID";
private int limit = 30;

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setUID(UID).setLimit(limit).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
var messagesRequest:MessagesRequest?=null
val UID:String="UID"
val limit:Int=30
   messagesRequest=MessagesRequest.MessagesRequestBuilder().setUID(UID).setLimit(limit).build()
       messagesRequest?.fetchPrevious(object:CometChat.CallbackListener<List<BaseMessage>>(){
       override fun onSuccess(p0: List<BaseMessage>?) {
       if (p0 is TextMessage){
         Log.d(TAG, "Text message received successfully: " + p0.toString())
         
         }
         if (p0 is MediaMessage){
         Log.d(TAG, "Media message received successfully: " + p0.toString())
         }
         
}
      override fun onError(p0: CometChatException?) {
      Log.d(TAG, "Message fetching failed with exception: " + p0?.message)
      
      }
})

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation.

For a Particular Group

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation for any group provided the logged-in user is part of that group. For this use case, it is mandatory to set the GUID parameter using the setGUID() method of the builder. This GUID is the unique identifier of the group for which the messages are to be fetched.

private String GUID = "GUID";
private int limit = 30;

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setGUID(GUID).setLimit(limit).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});
var messagesRequest:MessagesRequest?=null
val UID:String="GUID"
val limit:Int=30
   messagesRequest=MessagesRequest.MessagesRequestBuilder().setGUID(GUID).setLimit(limit).build()
       messagesRequest?.fetchPrevious(object:CometChat.CallbackListener<List<BaseMessage>>(){
       override fun onSuccess(p0: List<BaseMessage>?) {
       if (p0 is TextMessage){
         Log.d(TAG, "Text message received successfully: " + p0.toString())
         
         }
         if (p0 is MediaMessage){
         Log.d(TAG, "Media message received successfully: " + p0.toString())
         }
         
}
      override fun onError(p0: CometChatException?) {
      Log.d(TAG, "Message fetching failed with exception: " + p0?.message)
      
      }
})

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation.

Search Messages

Along with the other parameters mentioned above, you can use the setSearchKeyword() method provided by the MessagesRequestBuilder class. This method takes a string as input. This is the string that is to be searched amongst the messages. You can refer to the below code snippet for implementing the search messages feature:

private int limit = 30;

MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setSearchKeyword("Hello").setLimit(limit).build();

messagesRequest.fetchPrevious(new CometChat.CallbackListener<List<BaseMessage>>() {
  @Override
  public void onSuccess(List <BaseMessage> list) {
    for (BaseMessage message: list) {
      if (message instanceof TextMessage) {
        Log.d(TAG, "Text message received successfully: " +
          ((TextMessage) message).toString());
      } else if (message instanceof MediaMessage) {
        Log.d(TAG, "Media message received successfully: " +
          ((MediaMessage) message).toString());
      }
    }
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message fetching failed with exception: " + e.getMessage());
  }
});

This can be used to fetch all the messages that contain the string in a paginated way. Calling the fetchPrevious() method on the same object repeatedly allows you to fetch all the messages with the keyword specified in all your conversations. This parameter along with setUID() or setGUID() can be used to search messages in any particular group or one to one conversations

Unread Messages Count

In other words, as a logged-in user, how do I find out the number of unread messages that I have?

For a Particular One-on-one Conversation

In other words, how do I find out the number of unread messages I have from a particular user?

In order to get the unread message count for a particular user (with respect to the logged-in user), you can use the getUnreadMessageCountForUser().

This method has the two variants:

CometChat.getUnreadMessageCountForUser(String UID, Callbacks);

If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true:

CometChat.getUnreadMessageCountForUser(String UID, boolean hideMessagesFromBlockedUsers, Callbacks);
private String UID = "SUPERHERO1"
  
CometChat.getUnreadMessageCountForUser(UID, new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
    public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
        // handle success
  }

  @Override
    public void onError(CometChatException e) {
        // handle error
  }
});
val UID:String="SUPERHERO1"
        
CometChat.getUnreadMessageCountForUser(UID, object : CometChat.CallbackListener<HashMap<String, Int>>() {
       override fun onSuccess(stringIntegerHashMap: HashMap<String, Int>) {
              Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}")
            }
       override fun onError(e: CometChatException) {
              Log.d(TAG,"onError: ${e.message}")
            }
    })

In the onSuccess() callback, you will receive a hashmap which will contain the UID of the user as the key and the unread message count as the value.

For a Particular Group Conversation

In other words, how do I find out the number of unread messages I have in a single group?

In order to get the unread message count for a particular group, you can use the getUnreadMessageCountForGroup().

This method has two variants:

CometChat.getUnreadMessageCountForGroup(String GUID, Callbacks);

If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:

CometChat.getUnreadMessageCountForGroup(String GUID, boolean hideMessagesFromBlockedUsers, Callbacks);
private String GUID = "SUPERGROUP"
  
CometChat.getUnreadMessageCountForGroup(GUID, new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
    public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
        // handle success
  }

  @Override
    public void onError(CometChatException e) {
        // handle error
  }
});
val GUID:String="SUPERGROUP"

 CometChat.getUnreadMessageCountForGroup(GUID, object : CometChat.CallbackListener<HashMap<String, Int>>() {
        override fun onSuccess(stringIntegerHashMap: HashMap<String, Int>) {
             Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}")
        }

        override fun onError(e: CometChatException) {
             Log.d(TAG,"onError: ${e.message}")
        }
     })

In the onSuccess() callback, you will receive a hashmap which will contain the GUID of the group as the key and the unread message count as the value.

For All One-on-one & Group Conversations

In other words, how do I find out the number of unread messages for every one-on-one and group conversation?

In order to get all the unread message counts, you can use the getUnreadMessageCount() method.
This method has two variants:

CometChat.getUnreadMessageCount(Callbacks);

If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:

CometChat.getUnreadMessageCount(boolean hideMessagesFromBlockedUsers, Callbacks);
CometChat.getUnreadMessageCount(new CometChat.CallbackListener<HashMap<String, HashMap<String, Integer>>>() {
  @Override
    public void onSuccess(HashMap<String, HashMap<String, Integer>> stringHashMapHashMap) {
        // handle success
  }

  @Override
    public void onError(CometChatException e) {
        // handle error
  }
});
CometChat.getUnreadMessageCount(object : CometChat.CallbackListener<HashMap<String, HashMap<String,Int>>>() {
          override fun onSuccess(p0: HashMap<String, HashMap<String, Int>>?) {
                Log.d(TAG,"onSuccess: ${p0?.size}")
            }

           override fun onError(e: CometChatException) {
                Log.d(TAG,"onError: ${e.message}")
            }
        })

In the onSuccess() callback, you will receive a hashmap having two keys:

  1. user - The value for this key holds another hashmap that holds the UIDs of users and their corresponding unread message counts.
  2. group - The value for this key holds another hashmap that holds the GUIDs of groups and their corresponding unread message counts.

For All One-on-one Conversations

In other words, how do I find out the number of unread messages I have for every user?

In order to fetch the unread message counts for just the users, you can use the getUnreadMessageCountForAllUsers() method.

This method, just like others, has two variants:

CometChat.getUnreadMessageCountForAllUsers(Callbacks);

If you wish to ignore the messages from blocked users you can use the following syntax setting the boolean parameter to true:

CometChat.getUnreadMessageCountForAllUsers(boolean hideMessagesFromBlockedUsers, Callbacks);
CometChat.getUnreadMessageCountForAllUsers(new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
    public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
        // Handle Success
  }

  @Override
    public void onError(CometChatException e) {
        // Handle Error
  }

});
CometChat.getUnreadMessageCountForAllUsers(object : CometChat.CallbackListener<HashMap<String, Int>>() {
      override fun onSuccess(stringIntegerHashMap: HashMap<String, Int>) {
            Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}")
       }
      override fun onError(e: CometChatException) {
            Log.d(TAG,"onError: ${e.message}")
       }

  })

In the onSuccess() callback, you will receive a hashmap that will contain the UIDs of users as the key and the unread message counts as the values.

For All Group Conversations

In other words, how do I find out the number of unread messages for every group?

In order to fetch the unread message counts for all groups, you can use the getUnreadMessageCountForAllGroups() method.

This method has two variants:

CometChat.getUnreadMessageCountForAllGroups(Callbacks);

If you wish to ignore the messages from blocked users you can use the below syntax setting the boolean parameter to true:

CometChat.getUnreadMessageCountForAllGroups(boolean hideMessagesFromBlockedUsers, Callbacks);
CometChat.getUnreadMessageCountForAllGroups(new CometChat.CallbackListener<HashMap<String, Integer>>() {
  @Override
    public void onSuccess(HashMap<String, Integer> stringIntegerHashMap) {
        // Handle success
  }
  

  @Override
    public void onError(CometChatException e) {
    // Handle Error
  }
});
CometChat.getUnreadMessageCountForAllGroups(object : CometChat.CallbackListener<HashMap<String, Int>>() {
        override fun onSuccess(stringIntegerHashMap: HashMap<String, Int>) {
             Log.d(TAG,"onSuccess: ${stringIntegerHashMap.size}")
        }

        override fun onError(e: CometChatException) {
             Log.d(TAG,"onError: ${e.message}")
        }
})

In the onSuccess() callback, you will receive a hashmap which will contain the GUIDs of the groups as the key and the unread message counts as the values.

Updated 6 months ago


Receive Messages


Learn how to receive messages and fetch history & unread messages.

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.