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!

Messaging

Send a Text Message

To send a text message to any particular user or group, you need to use the sendMessage() method.

private String receiverID = "UID";
private String messageText = "Hello world!";
private String messageType = CometChatConstants.MESSAGE_TYPE_TEXT;
private String receiverType = CometChatConstants.RECEIVER_TYPE_USER;

TextMessage textMessage = new TextMessage(receiverID, messageText, messageType, receiverType);

CometChat.sendMessage(textMessage, new CometChat.CallbackListener<TextMessage>() {
  @Override
  public void onSuccess(TextMessage textMessage) {
    Log.d(TAG, "Message sent successfully: " + textMessage.toString());
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message sending failed with exception: " + e.getMessage());
  }
});
val receiverID:String="UID"
val messageText:String="Hello world!"
val messageType:String=CometChatConstants.MESSAGE_TYPE_TEXT
val receiverType:String=CometChatConstants.RECEIVER_TYPE_USER

val textMessage = TextMessage(receiverID, messageText, messageType,receiverType)

CometChat.sendMessage(textMessage, object : CometChat.CallbackListener<TextMessage>() {
   override fun onSuccess(p0: TextMessage?) {
      Log.d(TAG, "Message sent successfully: " + p0?.toString())               
   }

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

})
private String receiverID = "GUID";
private String messageText = "Hello world!";
private String messageType = CometChatConstants.MESSAGE_TYPE_TEXT;
private String receiverType = CometChatConstants.RECEIVER_TYPE_GROUP;

TextMessage textMessage = new TextMessage(receiverID, messageText, messageType, receiverType);

CometChat.sendMessage(textMessage, new CometChat.CallbackListener<TextMessage>() {
  @Override
  public void onSuccess(TextMessage textMessage) {
    Log.d(TAG, "Message sent successfully: " + textMessage.toString());
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message sending failed with exception: " + e.getMessage());
  }
});
val receiverID:String="GUID"
val messageText:String="Hello world!"
val messageType:String=CometChatConstants.MESSAGE_TYPE_TEXT
val receiverType:String=CometChatConstants.RECEIVER_TYPE_GROUP

val textMessage = TextMessage(receiverID, messageText, messageType,receiverType)

CometChat.sendMessage(textMessage, object : CometChat.CallbackListener<TextMessage>() {
   override fun onSuccess(p0: TextMessage?) {
      Log.d(TAG, "Message sent successfully: " + p0?.toString())
    }

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

})

To send a message you need to create an object of the TextMessage class. The constructor of the TextMessage class takes the following mandatory parameters:

Parameter
Description

receiverID

The UID or GUID of the recipient

messageText

The text message to be sent

messageType

The type of the message that needs to be sent, which in this case is text.

receiverType

The type of the receiver to whom the message is to be sent i.e CometChatConstants.RECEIVER_TYPE_USER (user) or CometChatConstants.RECEIVER_TYPE_GROUP (group)

On success, you will receive an object of the TextMessage class containing all the information related to the sent text message.

Send Media Message

To send a media message to any user or group, you need to use the sendMediaMessage() method.

private String receiverID = "UID";
private String messageType = CometChatConstants.MESSAGE_TYPE_IMAGE;
private String receiverType = CometChatConstants.RECEIVER_TYPE_USER;
private String filePath = "/storage/emulated/0/Download/46.jpg";

MediaMessage mediaMessage = new MediaMessage(receiverID,new File(filePath),messageType,receiverType);

CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener<MediaMessage>() {
  @Override
  public void onSuccess(MediaMessage mediaMessage) {
    Log.d(TAG, "Media message sent successfully: " + mediaMessage.toString());
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Media message sending failed with exception: " + e.getMessage());
  }
});
val recreceiverID:String = "UID"
val messageType:String = CometChatConstants.MESSAGE_TYPE_IMAGE
val receiverType:String = CometChatConstants.RECEIVER_TYPE_USER
val filePath:String = "/storage/emulated/0/Download/46.jpg"

val mediaMessage = MediaMessage(recreceiverID, File(filePath), messageType, receiverType)
       
CometChat.sendMediaMessage(mediaMessage, object : CometChat.CallbackListener<MediaMessage>() {
   override fun onSuccess(p0: MediaMessage?) {
     Log.d(TAG, "Media message sent successfully: " + p0?.toString())      
   }
  
   override fun onError(p0: CometChatException?) {
    Log.d(TAG, "Message sending failed with exception: " + p0?.message)             
   }
})
private String receiverID = "GUID";
private String messageType = CometChatConstants.MESSAGE_TYPE_IMAGE;
private String receiverType = CometChatConstants.RECEIVER_TYPE_GROUP;
private String filePath = "/storage/emulated/0/Download/46.jpg";

MediaMessage mediaMessage = new MediaMessage(receiverID,new File(filePath),messageType,receiverType);

CometChat.sendMediaMessage(mediaMessage, new CometChat.CallbackListener<MediaMessage>() {
  @Override
  public void onSuccess(MediaMessage mediaMessage) {
    Log.d(TAG, "Media message sent successfully: " + mediaMessage.toString());
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Media message sending failed with exception: " + e.getMessage());
  }
});
val recreceiverID:String = "GUID"
val messageType:String = CometChatConstants.MESSAGE_TYPE_IMAGE
val receiverType:String = CometChatConstants.RECEIVER_TYPE_GROUP
val filePath:String = "/storage/emulated/0/Download/46.jpg"

val mediaMessage = MediaMessage(recreceiverID, File(filePath), messageType, receiverType)
       
CometChat.sendMediaMessage(mediaMessage, object : CometChat.CallbackListener<MediaMessage>() {
   override fun onSuccess(p0: MediaMessage?) {
     Log.d(TAG, "Media message sent successfully: " + p0?.toString())      
   }
  
   override fun onError(p0: CometChatException?) {
    Log.d(TAG, "Message sending failed with exception: " + p0?.message)             
   }
})

To send a media message you need to create an object of the MediaMessage class. The constructor of the MediaMessage class takes the following mandatory parameters:

Parameter
Description

receiverId

The UID or GUID of the recipient

file

The file object to be sent

messageType

The type of the message that needs to be sent which in this case can be:
1.CometChatConstants.MESSAGE_TYPE_IMAGE (image)
2.CometChatConstants.MESSAGE_TYPE_VIDEO (video)
3.CometChatConstants.MESSAGE_TYPE_AUDIO (audio)
4.CometChatConstants.MESSAGE_TYPE_FILE (file)

receiverType

The type of the receiver to whom the message is to be sent i.e CometChatConstants.RECEIVER_TYPE_USER (user) or CometChatConstants.RECEIVER_TYPE_GROUP (group)

On success, you will receive an object of the MediaMessage class containing all the information related to the sent media message.

Send Custom Message

CometChat SDK allows you to send a completely custom message across. You can use this feature to send messages that do not fit in any default categories provided. In order to send a custom message, you need to use the sendCustomMessage() method.

The sendCustomMessage() methods takes an object of the CustomMessage which can be obtained using the below two constructor:


CustomMessage customMessage = new CustomMessage(receiverId, receiverType,customType customData)

The above constructor, helps you create a custom message with the message type set to whatever is passed to the constructor and the category set to custom.

The parameters involved are:

  1. receiverId - Unique id of the user or group to which the message is to be sent.
  2. receiverType - Type of the receiver i.e user or group
  3. customType - custom message type that you need to set
  4. customData - The data to be passed as the message in the form of a JSONObject.

You can also use the subType field of the CustomMessage class to set a specific type for the CustomeMessage. This can be achieved using the setSubtype() method.

Once the object of CustomMessage class is ready you can send the custom message using the sendCustomMessage() method.

private String UID = "UID";
private String customType = "LOCATION";

JSONObject customData = new JSONObject();
customData.put("lattitue","19.0760");
customData.put("longitude","72.8777");

CustomMessage customMessage = new CustomMessage(UID,CometChatConstants.RECEIVER_TYPE_USER,customType, customData);
CometChat.sendCustomMessage(customMessage, new CometChat.CallbackListener<CustomMessage>() {
  @Override
    public void onSuccess(CustomMessage customMessage) {
    Log.d(TAG, customMessage.toString());
  }
  
  @Override
    public void onError(CometChatException e) {
    Log.d(TAG, e.getMessage());
  }
});
val UID="UID"

val customData=JSONObject()
customData.put("lattitue","19.0760")
customData.put("longitude","72.8777")

val customMessage = CustomMessage(UID, CometChatConstants.RECEIVER_TYPE_USER, customData)
customMessage.subType = "location"
  
CometChat.sendCustomMessage(customMessage, object :CometChat.CallbackListener<CustomMessage>() {
         override fun onSuccess(customMessage: CustomMessage) {
             Log.d(TAG, customMessage.toString())
        }

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

The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups.

In success, you will receive an object of the CustomMessage class

Send Custom Data along with a Message

To send custom data along with either a text or a media message, you can use the metadata field provided in both TextMessage and MediaMessage class. The metadata field is a JSONObject which will be received as it was sent without any processing from CometChat. It can be used to send any additional data that needs to be sent along with a message.

private String receiverID = "UID";
private String messageText = "Hello world!";
private String messageType = CometChatConstants.MESSAGE_TYPE_TEXT;
private String receiverType = CometChatConstants.RECEIVER_TYPE_USER;

TextMessage textMessage = new TextMessage(receiverID, messageText, messageType, receiverType);

JSONObject metadataObject = new JSONObject("{\"latitude\":\"50.6192171633316\",\"longitude\":\"-72.68182268750002\"}");
textMessage.setMetadata(metadataObject);

CometChat.sendMessage(textMessage, new CometChat.CallbackListener<TextMessage>() {
  @Override
  public void onSuccess(TextMessage textMessage) {
    Log.d(TAG, "Message sent successfully: " + textMessage.toString());
  }
  @Override
  public void onError(CometChatException e) {
    Log.d(TAG, "Message sending failed with exception: " + e.getMessage());
  }
});
val receiverID:String="UID"
val messageText:String="Hello world!"
val messageType:String=CometChatConstants.MESSAGE_TYPE_TEXT
val receiverType:String=CometChatConstants.RECEIVER_TYPE_USER

val textMessage = TextMessage(receiverID, messageText, messageType,receiverType)

val metadataObject:JSONObject=JSONObject("{\"latitude\":\"50.6192171633316\",\"longitude\":\"-72.68182268750002\"}")

 textMessage.metadata=metadataObject

CometChat.sendMessage(textMessage, object : CometChat.CallbackListener<TextMessage>() {
   override fun onSuccess(p0: TextMessage?) {
      Log.d(TAG, "Message sent successfully: " + p0?.toString())               
   }

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

})

Custom data can be sent similarly for media messages (as well as to groups).

Receive Messages

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.

private String listenerID = "UNIQUE_LISTENER_ID";

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

CometChat.removeMessageListener(listenerID)

We suggest adding the listener in the onResume() method of the activity/fragment and removing the listener in the onPause() method.

IMPORTANT

The listeners only help you receive the real-time messages i.e when the user is online in the app and the listeners are added to receive the messages. To fetch previous messages for a user/group please refer to the Fetch Messages section.

Edit Message

In order to edit a message, you can use the editMessage() method. This method takes an object of the BaseMessage class. At the moment, you are only allowed to edit TextMessage and CustomMessage. Thus, the BaseMessage object must either be a Text or a Custom Message.

TextMessage updatedMessage = new TextMessage(message.getReceiverUid(), ((TextMessage)message).getText() + "edited", message.getType(),message.getReceiverType());

 updatedMessage.setId(message.getId());

CometChat.editMessage(updatedMessage, new CometChat.CallbackListener<BaseMessage>() {
  @Override
    public void onSuccess(BaseMessage message) {

  }

  @Override
    public void onError(CometChatException e) {
    
  }

});
val updatedMessage = TextMessage(message.receiverUid, (message as TextMessage).text + "edited", message.type, message.receiverType)

updatedMessage.id=message.id
  
CometChat.editMessage(updatedMessage, object: CometChat.CallbackListener<BaseMessage>() {
         override fun onSuccess(message: BaseMessage) {
            Log.d(TAG,"editMessage onSuccess: ${message}")
          }

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

   })

The object of the edited message will be returned in the onSucess() callback method of the listener. The message object will contain the editedAt field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The editedBy field is also set to the UID of the user who edited the message.

In order to receive real-time events for message being edited, you need to override the onMessageEdited() method of the MessageListener class.

CometChat.addMessageListener(listenerID, new CometChat.MessageListener() {

@Override
  public void onMessageEdited(BaseMessage message) {
  Log.d(TAG, "Message Edited");
}
});
CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() {
      fun onMessageEdited(message: BaseMessage) {
                Log.d(TAG, "Message Edited")
            }
     })

Delete Message

In case you have to delete a message, you can use the deleteMessage() method. This method takes the message ID of the message to be deleted.

 CometChat.deleteMessage(12345, new CometChat.CallbackListener<BaseMessage>() {
   @Override
     public void onSuccess(BaseMessage message) {
     Log.d(TAG, "Message deleted successfully at : " + message.getDeletedAt());
   }

   @Override
     public void onError(CometChatException e) {
     Log.d(TAG, e.getMessage());
   }
 
 });
CometChat.deleteMessage(12345,object : CometChat.CallbackListener<BaseMessage>(){
    override fun onSuccess(message: BaseMessage) {
         Log.d(TAG, "deleteMessage onSuccess : " + message.deletedAt)
         }

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

  })

Once the message is deleted, In the onSuccess() callback, you get an object of the BaseMessage class, with the deletedAt field set with the timestamp of the time the message was deleted. Also, the deletedBy field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages.

In order to receive real-time events for a message being deleted, you need to override the onMessageDeleted() method of the MessageListener class.

CometChat.addMessageListener(listenerID, new CometChat.MessageListener() {
  @Override
   public void onMessageDeleted(BaseMessage message) {
      Log.d(TAG, "Message Edited");
    }
});
CometChat.addMessageListener(listenerID, object : CometChat.MessageListener() {
       override fun onMessageDeleted(message: BaseMessage?) {
               Log.d(TAG, "Message Edited")
          }
    })

Also, while fetching the list of messages, if the message with ID of 100 was edited or deleted and the total number of messages in the conversation are 110, the 111st message fetched will be an Action message informing the user that the message with the ID 100 has been edited/deleted. To get the message object from the Action message object, you can use the action.getActionOn() method which can be cast to the BaseMessage object.

Important

In order to edit or delete a message you need to be either the sender of the message or the admin/moderator of the group in which the message was sent.

Fetch Messages

In order to fetch messages in bulk, the CometChat SDK provides the MessagesRequest class. To use this class i.e to create an object of the MessagesRequest class, you need to use the MessagesRequestBuilder class. The MessagesRequestBuilder class allows you to set the parameters based on which the messages are to be fetched.

The MessagesRequestBuilder class allows you to set the below parameters :

  1. setUID(String UID) - This method sets the UID of the user for which the messages are to be fetched i.e. The messages fetched will be a part of the conversation between the logged in user and the UID set using the setUID() method.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setUID("uid").build();
  1. setGUID(String GUID) - This method sets the GUID of the group for which the messages are to be fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setGUID("guid").build();
  1. setMessageId(int messageId) - This method sets the messageID before or after which the messages are to be fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setMessageId(100).build();
  1. setTimestamp(long timestamp) - This method sets the timestamp before or after which the messages are to be fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setTimestamp(1517221231).build();
  1. setUnread(boolean unread) - This method sets the unread parameter which determines if only the unread messages need to be fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setUnread(true).build();
  1. setUndelivered(boolean undelivered) - This method sets the undelivered parameter which determines if only the undelivered messages need to be fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setUndelivered(true).build();
  1. setLimit(int limit) - This method sets the limit i.e. the number of messages that should be fetched in a single iteration.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().setLimit(30).build();
  1. hideMessagesFromBlockedUsers(boolean block) - This parameter determines if the messages from blocked users are to be hidden in the list of messages fetched.
MessagesRequest messagesRequest = new MessagesRequest.MessagesRequestBuilder().hideMessagesFromBlockedUsers(true).build();
  1. setSearchKeyword() - This parameter helps you get messages with the keyword specified. Once this parameter is set, the request will return messages containing the keyword.

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

Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the MessagesRequest class.

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

The object of the MessagesRequest class can be used to call one of the two below methods:

  1. fetchPrevious() - this method fetches the messages prior to the parameters set.

  2. fetchNext() - this method fetches the messages after the parameters set.

Calling the fetchPrevious() and fetchNext() on the same object of the MessagesRequest class, you can get the paginated list of messages till all the messages for the combination of the parameters set are fetched.

Using the above set of methods, various combinations of messages can be fetched.

1. Fetch all messages:

Using the same MessagesRequest class discussed above, you can fetch all the messages for a logged in user which involve his messages for all the User and Group conversations. Applying the filters using the MessagesRequestBuilder class, you can fetch messages either before or after a particular messageId or timestamp.

The below code snippet shows how to fetch the latest 50 messages for the logged in user which include messages to and from the logged in user as a part of any User or Group conversations.

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.

2. Fetch Messages when User was offline.

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 him as he was 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 he/she was offline.

Below code snippet 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 conversation too.

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

3. Fetch messages for a User 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.

4. Fetch Messages for a Group 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 for any group provided you have joined the 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.

Get all unread messages.

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 a TextMessage or a MediaMessage. You can use the instanceOf operator to check the type of object.

Messaging


Suggested Edits are limited on API Reference Pages

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