Skip to main content
Version: v4

Methods

Overview

The UI Kit's core function is to extend the Chat SDK, essentially translating the raw data and functionality provided by the underlying methods into visually appealing and easy-to-use UI components.

To effectively manage and synchronize the UI elements and data across all components in the UI Kit, we utilize internal events. These internal events enable us to keep track of changes in real-time and ensure that the UI reflects the most current state of data.

The CometChat UI Kit has thoughtfully encapsulated the critical Chat SDK methods within its wrapper to efficiently manage internal eventing. This layer of abstraction simplifies interaction with the underlying CometChat SDK, making it more user-friendly for developers.

Methods

You can access the methods using the CometChatUIKit class. This class provides access to all the public methods exposed by the CometChat UI Kit.

Init

As a developer, you need to invoke this method every time before you use any other methods provided by the UI Kit.

This initialization is a critical step that ensures the UI Kit and Chat SDK function correctly and as intended in your application. Typical practice is to make this one of the first lines of code executed in your application's lifecycle when it comes to implementing CometChat.

info

Make sure you replace the APP_ID, REGION and AUTH_KEY with your CometChat App ID, Region and Auth Key in the below code. The Auth Key is an optional property of the UIKitSettings Class. It is intended for use primarily during proof-of-concept (POC) development or in the early stages of application development. You can use the Auth Token to log in securely.

CometChatUIKit.init(Context context, UIKitSettings authSettings, CometChat.CallbackListener<String> callbackListener)

As a developer, the UIKitSettings is an important parameter of the init() function. It functions as a base settings object, housing properties such as appId, region, and authKey, contained within UIKitSettings.

Here's the table format for the properties available in UIKitSettings:

MethodTypeDescription
setAppIdStringSets the unique ID for the app, available on dashboard
setRegionStringSets the region for the app ('us' or 'eu')
setAuthKeyStringSets the auth key for the app, available on dashboard
subscribePresenceForAllUsersStringSets subscription type for tracking the presence of all users
subscribePresenceForFriendsStringSets subscription type for tracking the presence of friends
subscribePresenceForRolesStringSets subscription type for tracking the presence of users with specified roles
setAutoEstablishSocketConnectionBooleanConfigures if web socket connections will established automatically on app initialization or be done manually, set to true by default
setAIFeaturesList<AIExtensionDataSource>Sets the AI Features that need to be added in UI Kit
setExtensionsList<ExtensionsDataSource>Sets the list of extension that need to be added in UI Kit

The concluding code block:

UIKitSettings uiKitSettings = new UIKitSettings.UIKitSettingsBuilder()
.setRegion(your_region)
.setAppId(your_appID)
.setAuthKey(your_authKey)
.subscribePresenceForAllUsers().build();


CometChatUIKit.init(context, uiKitSettings, new CometChat.CallbackListener<String>() {
@Override
public void onSuccess(String response) {
Log.i(TAG, "CometChat init onSuccess: "+response);

@Override
public void onError(CometChatException e) {
Log.e(TAG, "CometChat init exception: "+e);
}
});

Login using Auth Key

Only the UID of a user is needed to log in. This simple authentication procedure is useful when you are creating a POC or if you are in the development phase. For production apps, we suggest you use AuthToken instead of Auth Key.

CometChatUIKit.login(String uid, CometChat.CallbackListener <User> callbackListener)

The concluding code block:

CometChatUIKit.login(UID, new CometChat.CallbackListener<User>() {
@Override
public void onSuccess(User user) {
Log.i(TAG, "CometChat Login Successful : " + user.toString());
}
@Override
public void onError(CometChatException e) {
Log.e(TAG, "CometChat Login Failed : " + e.getMessage());
}
});

Login using Auth Token

This advanced authentication procedure does not use the Auth Key directly in your client code thus ensuring safety.

  1. Create a User via the CometChat API when the user signs up in your app.

  2. Create an Auth Token via the CometChat API for the new user and save the token in your database.

  3. Load the Auth Token in your client and pass it to the loginWithAuthToken() method.

    CometChatUIKit.loginWithAuthToken(String authToken, CometChat.CallbackListener <User> callbackListener)

    The concluding code block:

    CometChatUIKit.loginWithAuthToken(AuthToken, new CometChat.CallbackListener<User>() {
    @Override
    public void onSuccess(User user) {
    Log.i(TAG, "CometChat Login Successful : " + user.toString());
    }
    @Override
    public void onError(CometChatException e) {
    Log.e(TAG, "CometChat Login Failed : " + e.getMessage());
    }
    });

Logout

The CometChat UI Kit and Chat SDK effectively handle the session of the logged-in user within the framework. Before a new user logs in, it is crucial to clean this data to avoid potential conflicts or unexpected behavior. This can be achieved by invoking the .logout() function

    CometChatUIKit.logout(CometChat.CallbackListener <String> callbackListener)

The concluding code block:

CometChatUIKit.logout(new CometChat.CallbackListener<String>() {
@Override
public void onSuccess(String s) {
// your action on logout
}
@Override
public void onError(CometChatException e) {
}
});

Create User

As a developer, you can dynamically create users on CometChat using the .createUser() function. This can be extremely useful for situations where users are registered or authenticated by your system and then need to be created on CometChat.

CometChatUIKit.createUser(User user, CometChat.CallbackListener <User> callbackListener);

The concluding code block:

User user = new User("user_uid","user_name");
user.setAvatar("user_avatar_url");

CometChatUIKit.createUser(user, new CometChat.CallbackListener<User>() {
@Override
public void onSuccess(User user) {
}
@Override
public void onError(CometChatException e) {
}
});

Base Message

Text Message

As a developer, if you need to send a text message to a single user or a group, you'll need to utilize the sendMessage() function. This function requires a TextMessage object as its argument, which contains the necessary information for delivering the message.

CometChatUIKit.sendTextMessage(TextMessage textMessage, CometChat.CallbackListener <TextMessage> messageCallbackListener)

It's essential to understand the difference between CometChatUIKit.sendTextMessage() and CometChat.sendTextMessage(). When you use CometChatUIKit.sendTextMessage(), it automatically adds the message to the MessagesComponent and ConversationsComponent, taking care of all related cases for you. On the other hand, CometChat.sendTextMessage() only sends the message and doesn't automatically update these components in the UI Kit.

The concluding code block:

TextMessage textMessage = new TextMessage("receiver_uid", "your_text_message", CometChatConstants.RECEIVER_TYPE_USER);
CometChatUIKit.sendTextMessage(textMessage, new CometChat.CallbackListener<TextMessage>() {
@Override
public void onSuccess(TextMessage message) {
}
@Override
public void onError(CometChatException e) {
}
});

Media Message

As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the sendMediaMessage() function. This function requires a MediaMessage object as its argument, which contains the necessary information for delivering the message.

CometChatUIKit.sendMediaMessage(MediaMessage mediaMessage, CometChat.CallbackListener <MediaMessage> messageCallbackListener)

It's essential to understand the difference between CometChatUIKit.sendMediaMessage() and CometChat.sendMediaMessage(). When you use CometChatUIKit.sendMediaMessage(), it automatically adds the message to the MessagesComponent and ConversationsComponent, taking care of all related cases for you. On the other hand, CometChat.sendMediaMessage() only sends the message and doesn't automatically update these components in the UI Kit.

The concluding code block:

MediaMessage mediaMessage = new MediaMessage("receiver_uid", new File("your_filePath"), CometChatConstants.MESSAGE_TYPE_FILE, CometChatConstants.RECEIVER_TYPE_USER);

CometChatUIKit.sendMediaMessage(mediaMessage, new CometChat.CallbackListener<MediaMessage>() {
@Override
public void onSuccess(MediaMessage mediaMessage) {
}
@Override
public void onError(CometChatException e) {
}
});

Custom Message

As a developer, if you need to send a media message to a single user or a group, you'll need to utilize the sendCustomMessage() function. This function requires a CustomMessage object as its argument, which contains the necessary information for delivering the message.

CometChatUIKit.sendCustomMessage(CustomMessage customMessage, CometChat.CallbackListener <CustomMessage> messageCallbackListener)

It's essential to understand the difference between CometChatUIKit.sendCustomMessage() and CometChat.sendCustomMessage(). When you use CometChatUIKit.sendCustomMessage(), it automatically adds the message to the MessagesComponent and ConversationsComponent, taking care of all related cases for you. On the other hand, CometChat.sendCustomMessage() only sends the message and doesn't automatically update these components in the UI Kit.

The concluding code block:

String customType = "your_message_type";
JSONObject customData = new JSONObject();

customData.put("key1","value1");
customData.put("key2","value2");
customData.put("key3","value3");
customData.put("key4","value4");

CustomMessage customMessage = new CustomMessage("receiver_uid", CometChatConstantsRECEIVER_TYPE_USER,customType, customData);

CometChatUIKit.sendCustomMessage(customMessage, new CometChat.CallbackListener<CustomMessage>() {
@Override
public void onSuccess(CustomMessage mediaMessage) {
}
@Override
public void onError(CometChatException e) {
}
});

Note: To display custom messages in the MessageList, you must create and register a new MessageTemplate that defines how to render your custom message type.


Interactive Message

Form Message

As a developer, if you need to send a Form message to a single user or a group, you'll need to utilize the sendFormMessage() function. This function requires a FormMessage object as its argument, which contains the necessary information to create a form bubble for that messages

CometChatUIKit.sendFormMessage(FormMessage formmessage, CometChat.CallbackListener <FormMessage> messageCallbackListener)

The concluding code block:

CometChatMessages cometChatMessages = findViewById(R.id.messages);
cometChatMessages.setUser(user);

List<ElementEntity> elementEntities = new ArrayList<>();
//here we have created the object to display the TextInput into the form
TextInputElement textInputElement1 = new TextInputElement("element1", "Name");
TextInputElement textInputElement2 = new TextInputElement("element2", "Last Name");
TextInputElement textInputElement3 = new TextInputElement("element3", "Address");
textInputElement3.setMaxLines(5);
elementEntities.add(textInputElement1);
elementEntities.add(textInputElement2);
elementEntities.add(textInputElement3);


//here we have created the navigation action which will executated on a click of button
URLNavigationAction urlNavigationAction = new URLNavigationAction("https://www.cometchat.com/");

ButtonElement submitElement = new ButtonElement("idSubmit", "submit", urlNavigationAction);
submitElement.setDisableAfterInteracted(true);
FormMessage formMessage = new FormMessage("uid-1001", UIKitConstants.ReceiverType.USER, elementEntities, submitElement);
formMessage.setTitle("Socity Survey");
formMessage.setAllowSenderInteraction(true); // this will confirm if sender can interact with that form or not
formMessage.setSender(CometChatUIKit.getLoggedInUser());
formMessage.setSentAt(System.currentTimeMillis() / 1000);
formMessage.setReceiver(user); // set Receiver user/group object

CometChatUIKit.sendFormMessage(formMessage, false, new CometChat.CallbackListener<FormMessage>() {
@Override
public void onSuccess(FormMessage formMessage) {

}

@Override
public void onError(CometChatException e) {
e.printStackTrace();
}
});

Card Message

As a developer, if you need to send a Card message to a single user or a group, you'll need to utilize the sendCardMessage() function. This function requires a CardMessage object as its argument, which contains the necessary information to create a card bubble for the messages

CometChatUIKit.sendCardMessage(CardMessage cardMessage, CometChat.CallbackListener <CardMessage> messageCallbackListener)

The concluding code block:

List<BaseInteractiveElement> elementEntities = new ArrayList<>();

URLNavigationAction urlNavigationAction = new URLNavigationAction("https://www.cometchat.com/");

ButtonElement buttonElement = new ButtonElement("idbtn", "submit", urlNavigationAction);
buttonElement.setDisableAfterInteracted(true); // button will be disable after interacted
buttonElement.setText("Learn more");

elementEntities.add(buttonElement);
// Create a new instance of CardMessage
CardMessage cardMessage = new CardMessage(receiverId, receivertype, "Decorative Text to show on Card", elementEntities);

cardMessage.setImageUrl("https://anyImageUrl.com"); // here you can set the Image url to the Card Message
cardMessage.setSender(CometChatUIKit.getLoggedInUser());
cardMessage.setSentAt(System.currentTimeMillis() / 1000);
cardMessage.setReceiver(user); //here receiver user or group object need to be set
CometChatUIKit.sendCardMessage(cardMessage, false, new CometChat.CallbackListener<CardMessage>() {
@Override
public void onSuccess(CardMessage cardMessage) {

}

@Override
public void onError(CometChatException e) {
e.printStackTrace();
}
});

Scheduler Message

As a developer, if you need to send a Scheduler message to a single user or a group, you'll need to utilize the sendCardMessage() function. This function requires a SchedulerMessage object as its argument, which contains the necessary information to create a SchedulerMessage bubble for the messages

CometChatUIKit.sendSchedulerMessage(SchedulerMessage schedulerMessage, CometChat.CallbackListener <SchedulerMessage> messageCallbackListener)

The concluding code block:

SchedulerMessage schedulerMessage = new SchedulerMessage();
schedulerMessage.setDuration(60);
schedulerMessage.setAllowSenderInteraction(true); // true to set the sender as the scheduler
schedulerMessage.setTitle("Meet Dr. Jackob");
schedulerMessage.setBufferTime(15);
schedulerMessage.setAvatarUrl("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRdRz0HEBl1wvncmX6rU8wFrRDxt2cvn2Dq9w&usqp=CAU");
schedulerMessage.setGoalCompletionText("Meeting Scheduled Successfully!!");

TimeZone timeZone = TimeZone.getDefault();
schedulerMessage.setTimezoneCode(timeZone.getID());
schedulerMessage.setDateRangeStart("2024-01-01");
schedulerMessage.setDateRangeEnd("2024-12-31");
schedulerMessage.setReceiverUid("cometchat-uid-1");

HashMap<String, List<TimeRange>> availability = new HashMap<>();
availability.put("monday", Arrays.asList(new TimeRange("0000", "1359")));
availability.put("tuesday", Arrays.asList(new TimeRange("0000", "1559")));
availability.put("wednesday", Arrays.asList(new TimeRange("0000", "0659")));
availability.put("thursday", Arrays.asList(new TimeRange("0000", "0959")));
availability.put("friday", Arrays.asList(new TimeRange("0000", "1059")));
schedulerMessage.setAvailability(availability);
APIAction clickAction = new APIAction("https://www.example.com", "POST", "data");

ButtonElement scheduleElement = new ButtonElement("21", "Submit", clickAction);
schedulerMessage.setScheduleElement(scheduleElement);

schedulerMessage.setReceiverType(CometChatConstants.RECEIVER_TYPE_USER);
schedulerMessage.setSender(CometChatUIKit.getLoggedInUser());
schedulerMessage.setSentAt(System.currentTimeMillis() / 1000);
schedulerMessage.setReceiver(user);

CometChatUIKit.sendSchedulerMessage(schedulerMessage,false, new CometChat.CallbackListener<SchedulerMessage>() {
@Override
public void onSuccess(SchedulerMessage schedulerMessage) {
// SchedulerMessage sent successfully
}

@Override
public void onError(CometChatException e) {
// Error occurred while sending SchedulerMessage
}
});

Custom InteractiveMessage

As a developer, if you need to send a Custom Interactive message to a single user or a group, you'll need to utilize the sendCustomInteractiveMessage() function. This function requires a CustomInteractiveMessage object as its argument.

CometChatUIKit.sendCustomInteractiveMessage(CustomInteractiveMessage customInteractiveMessage, CometChat.CallbackListener <CustomInteractiveMessage> messageCallbackListener)

The concluding code block:

JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("text", "custom Interactive message");
} catch (JSONException e) {
throw new RuntimeException(e);
}

CustomInteractiveMessage customInteractiveMessage = new CustomInteractiveMessage(receiverId,receiverType, jsonObject); //receiverType could be user/group
customInteractiveMessage.setSender(CometChatUIKit.getLoggedInUser());
customInteractiveMessage.setReceiver(user); // set Receiver user/group object

CometChatUIKit.sendCustomInteractiveMessage(customInteractiveMessage, false, new CometChat.CallbackListener<CustomInteractiveMessage>() {
@Override
public void onSuccess(CustomInteractiveMessage customInteractiveMessage) {

}
@Override
public void onError(CometChatException e) {
e.printStackTrace();
}
});

Note: To display custom messages in the MessageList, you must create and register a new MessageTemplate that defines how to render your custom message type.s