Tutorial: Creating a Xamarin Chat App Using Chat API

October 18, 2018

Saurabh Tripathi

Messaging apps are becoming omnipresent in today’s realm owing to the rise of Chat API.

We have put together a tutorial that will enable you to build a messaging app from scratch with no more than a few hundred lines of code without requiring a server or registration.

This article lays down the steps in a chronological order to build and implement Xamarin chat application using CometChat’s Xamarin Chat SDK which provides an easy method to send, fetch and receive messages in real time.


Step 1: Importing Packages

You can begin by creating a new Xamarin Android project.

The next step is to get Nuget Packages

Once the project is added, you must add packages from NuGet store. Search for “CometChat”, you will see 4 options: 2 for iOS and 2 for Android.

Add the following 2 packages for Android:

  • Xamarin.Android.CometChat
  • Xamarin.Android.CometChat.UI
Select the two packages as shown in the screenshot


Step 2: Initialize CometChat

The next step will be to point your CometChat instance to your domain. To do so you will need to initialize cometchat with the your API key and Licence key as follows:

InitializeCometChat(siteurl, licenseKey, apiKey, true, new CometChatCallback(success => successObject(success), fail => failObject(fail)));

site URL: this variable can be left blank for cloud license.

licenseKey: you can find this key in your admin panel once you sign up with CometChat.

Apikey: you can find this key in your admin panel once you sign up with CometChat.


Step 3: Create Users

Before starting you must create a sample user which you will need at the time of loggin in. Use the following “create user” API:

CreateUser(this,UID,username,"","","", new CometChatCallback(success => createSuccess(success), fail => createFail(fail)));

Where, UID: is the unique identification of the user. You can set this according to your preference, just make sure it’s unique.

For more details on this you can refer the documentation by following this link.


Step 4: Login

This is where you’ll need the UID which was created in step 3 (“create user” method). Follow the code below

LoginWithUID(this, UUID, new CometChatCallback(success => loginSuccess(success), fail => loginFail(fail)));

The sample code for the above methods is as follows :

MainActivity.cs
using Android.App;
using Android.Widget;
using Android.OS;
using Cometchat.Inscripts.Com.Cometchatcore.Coresdk;
using System;
using Android.Text;
using CometChatUIBinding.Additions;
using Org.Json;
using Android.Content;
using Firebase.Messaging;
using Android.Support.Design.Widget;
namespace CometChatCloudSample
{
    [Activity(Label = "CometChatCloudSample", MainLauncher = true, Icon = "@mipmap/icon")]
    public class MainActivity : Activity
    {
        int count = 1;
        CometChat cometchat;
        Context context = null;
        Activity activity = null;
        String siteurl = "SITEURL";
        String licenseKey = "COMETCHAT-XXXXX-XXXXX-XXXXX-XXXXX"; // Replace the value with your CometChat License Key here
        String apiKey = "xxxxxxxxxxxxxxxxxxxxxx"; // Replace the value with your CometChat API Key here
        
        Boolean isCometOnDemand = true;

        Random random;
        private Button btnInitializeChat;
        private EditText textUsername, textPassword;
        String username, password;
        String UID = null;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Main);
            btnInitializeChat = FindViewById<Button>(Resource.Id.buttonLogin);
            textUsername = FindViewById<EditText>(Resource.Id.editTextUsername);
            textPassword = FindViewById<EditText>(Resource.Id.editTextPassword);
            activity = this;
            random = new Random();
            cometchat = CometChat.GetInstance(this);
            initializeChat();

            // Set our view from the "main" layout resource
            btnInitializeChat.Click += delegate {
                username = textUsername.Text;
                password = textPassword.Text;
                if ((username != null && !TextUtils.IsEmpty(username))&& (password != null && !TextUtils.IsEmpty(password)))
                {
                    createUser(username, password);
                }
            }; 

            // Get our button from the layout resource,

            // and attach an event to it

        }

        private void initializeChat()
        {
            if (licenseKey != null && !TextUtils.IsEmpty(licenseKey))
            {
                if (apiKey != null && !TextUtils.IsEmpty(apiKey))
                {
                    cometchat.InitializeCometChat(siteurl, licenseKey, apiKey, isCometOnDemand, new CometChatCallback(success => successObject(success), fail => failObject(fail)));
                }
                else
                {
                    System.Console.WriteLine("Api Key Not Found ");
                }
            }
            else
            {
                System.Console.WriteLine("License Key Not Found  ");
            }
        }

        private void successObject(JSONObject success)
        {
            System.Console.WriteLine("InitializeCometChat success " + success.ToString());
        }

        private void failObject(JSONObject fail)
        {
            System.Console.WriteLine("InitializeCometChat Fail " + fail.ToString());
        }

        private void createUser(String username, String Password)
        {
            int randomnumber=random.Next(10, 1500);
            UID = randomnumber + username;
            System.Console.WriteLine("createUser  " + UID);
            cometchat.CreateUser(this,UID,username,"","","", new CometChatCallback(success => createSuccess(success), fail => createFail(fail)));
        }

        void createSuccess(JSONObject success)
        {
            System.Console.WriteLine("createSuccess success " + success.ToString());
            login(UID);
        }

        private void createFail(JSONObject fail)
        {
            System.Console.WriteLine("createFail Fail " + fail.ToString());
        }

        private void login(String UUID)
        {
            if (UUID != null && !TextUtils.IsEmpty(UUID))
            {
                cometchat.LoginWithUID(this, UUID, new CometChatCallback(success => loginSuccess(success), fail => loginFail(fail)));
            }
        }

        void loginSuccess(JSONObject success)
        {
            System.Console.WriteLine("LoginWithUID success " + success.ToString());
            Intent intent = new Intent(this, typeof(LauncherActivity));
            intent.AddFlags(ActivityFlags.ClearTask);
            intent.AddFlags(ActivityFlags.ClearTop);
            StartActivity(intent);
        }

        private void loginFail(JSONObject fail)
        {
            System.Console.WriteLine("LoginWithUID Fail " + fail.ToString());
        }
    }
}

Layout file for the above activity class

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ScrollView android:id="@+id/scrollviewParentLoginContainer"
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:wheel="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/color_white"
        android:fillViewport="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_gravity="center_horizontal"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/imageViewCometchatLogo"
                android:layout_width="250dp"
                android:layout_height="120dp"
                android:layout_marginBottom="16dp"
                android:layout_marginTop="20dp"
                android:adjustViewBounds="true"
                android:maxHeight="180dp"
                android:maxWidth="150dp"
                android:layout_centerHorizontal="true"
                android:tint="#000"
                android:src="@drawable/logo_login"/>

            <LinearLayout
                android:id="@+id/linearLayoutLoginContainer"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:gravity="center"
                android:orientation="vertical"
                android:layout_below="@+id/imageViewCometchatLogo"
                android:layout_alignParentBottom="true"
                android:layout_marginBottom="50dp"
                android:paddingLeft="24dp"
                android:paddingRight="24dp">
                <EditText
                    android:id="@+id/editTextUsername"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/TextLabel"
                    android:layout_marginBottom="5dp"
                    android:inputType="text"
                    android:maxWidth="300dp"
                    android:minWidth="250dp"
                    android:padding="10dp"
                    android:singleLine="true"
                    android:textColor="@color/colorAccent"
                    android:hint = "User Name"
                    android:textCursorDrawable="@null"
                    android:autoText="false"
                    android:textAllCaps="false"
                    android:linksClickable="false"
                    android:password="false"
                    android:phoneNumber="false"
                    android:allowUndo="false"
                    android:editable="true"
                    android:enabled="true"
                    android:visibility="visible"
                    android:textIsSelectable="false"
                    android:selectAllOnFocus="false"
                    android:scrollHorizontally="false"
                    android:cursorVisible="false"
                    android:freezesText="false"
                    android:clickable="false"
                    android:longClickable="false"
                    android:filterTouchesWhenObscured="false"
                    android:hapticFeedbackEnabled="false"
                    android:duplicateParentState="false"
                    android:isScrollContainer="false"
                    android:keepScreenOn="false"
                    android:saveEnabled="false"
                    android:soundEffectsEnabled="false" />
                <EditText
                    android:id="@+id/editTextPassword"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:theme="@style/TextLabel"
                    android:layout_marginBottom="5dp"
                    android:inputType="text"
                    android:maxWidth="300dp"
                    android:minWidth="250dp"
                    android:padding="10dp"
                    android:textColor="@color/colorAccent"
                    android:hint = "Password"
                    android:textCursorDrawable="@null"
                    android:enabled="true"
                    android:editable="true"
                    android:selectAllOnFocus="false"
                    android:scrollHorizontally="false"
                    android:cursorVisible="false"
                    android:singleLine="false"
                    android:freezesText="false"
                    android:clickable="false"
                    android:longClickable="false"
                    android:filterTouchesWhenObscured="false"
                    android:hapticFeedbackEnabled="false"
                    android:duplicateParentState="false"
                    android:isScrollContainer="false"
                    android:keepScreenOn="false"
                    android:saveEnabled="false"
                    android:soundEffectsEnabled="false" />

                 <Button
                    android:id="@+id/buttonLogin"
                    android:layout_width="match_parent"
                    android:layout_height="60dp"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="50dp"
                    android:background="@drawable/circular_button_background"
                    android:maxWidth="300dp"
                    android:minWidth="250dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginRight="10dp"
                    android:text="LOG IN"
                    android:textAllCaps="false"
                    android:textColor="@color/color_white"/>
            </LinearLayout>
          </RelativeLayout>
    </ScrollView>
</RelativeLayout>

This is how your app will run once you launch it using the above code:


Step 5: Launching Message UI

Once you are done with initialize and login you can launch cometchat. Use the following code:

LaunchCometChat(activity, fullscreen, new LaunchCallbacks(successObj => successCall(successObj), fail => failCall(fail), onChatroomInfo => ChatroomInfo(onChatroomInfo), onError => Error(onError), onLogout => Logout(onLogout), onMessageReceive => MessageReceive(onMessageReceive), onUserInfo => UserInfo(onUserInfo), onWindowClose => WindowClose(onWindowClose)));

Activity: The object of Activity from which you are launching the Chat window.

Fullscreen: If you want to launch the chat window in fullscreen or in a chat window.

The sample code for the above methods is as follows:

LauncherActivity.cs 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Cometchat.Inscripts.Com.Cometchatcore.Coresdk;
using CometChatUIBinding.Additions;
using Firebase.Messaging;
using Org.Json;

namespace CometChatCloudSample
{
    [Activity(Label = "LauncherActivity")]
    public class LauncherActivity : Activity
    {
        Context context = null;
        Activity activity = null;
        CometChat cometchat;
        private Button btnLaunchCometChat;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.LauncherActivity);
            activity = this;
            cometchat = CometChat.GetInstance(this);
            btnLaunchCometChat = FindViewById<Button>(Resource.Id.buttonLaunchCometChat);
            btnLaunchCometChat.Click += delegate {
                launchCometChat();
            };

            // Create your application here

        }

        private void launchCometChat()
        {
            cometchat.LaunchCometChat(activity, false, new LaunchCallbacks(successObj => successCall(successObj), fail => failCall(fail), onChatroomInfo => ChatroomInfo(onChatroomInfo), onError => Error(onError), onLogout => Logout(onLogout), onMessageReceive => MessageReceive(onMessageReceive), onUserInfo => UserInfo(onUserInfo), onWindowClose => WindowClose(onWindowClose)));
        }

        private void WindowClose(JSONObject onWindowClose)
        {
            System.Console.WriteLine("LaunchCometChat onWindowClose " + onWindowClose.ToString());
        }

        private void UserInfo(JSONObject onUserInfo)
        {
            System.Console.WriteLine("LaunchCometChat onUserInfo " + onUserInfo.ToString());
            String push_channel = onUserInfo.GetString("push_channel");
            System.Console.WriteLine("LaunchCometChat push_channel " + push_channel);
            FirebaseMessaging.Instance.SubscribeToTopic(push_channel);
        }

        private void MessageReceive(JSONObject onMessageReceive)
        {
            System.Console.WriteLine("LaunchCometChat onMessageReceive " + onMessageReceive.ToString());
        }

        private void Logout(JSONObject onLogout)
        {
            System.Console.WriteLine("LaunchCometChat onLogout" + onLogout.ToString());
        }

        private void Error(JSONObject onError)
        {
            System.Console.WriteLine("LaunchCometChat onError" + onError.ToString());
        }

        private void ChatroomInfo(JSONObject onChatroomInfo)
        {
            System.Console.WriteLine("LaunchCometChat onChatroomInfo" + onChatroomInfo.ToString());
        }

        private void failCall(JSONObject fail)
        {
            System.Console.WriteLine("LaunchCometChat " + fail.ToString());
        }

        private void successCall(JSONObject successObj)
        {
            System.Console.WriteLine("LaunchCometChat " + successObj.ToString());
        }
    }
}

And the Layout file LauncherActivity.axml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="25px"
    android:minHeight="25px">

    <Button
        android:id="@+id/buttonLaunchCometChat"
        android:layout_width="60dp"
        android:layout_height="60dp"
        android:layout_marginBottom="10dp"
        android:layout_marginTop="50dp"
        android:background="@drawable/circular_button_background"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:text="Launch CometChat"
        android:textAllCaps="false"
        android:textColor="@color/color_white"/>
</LinearLayout>

The output will be as follows:

This will be your login window

Once you have launched CometChat, you will be able to see your friend list like below:

CometChat has now integrated in your application

And this is it! You can now take the chat app for a test drive on two devices (one can be the emulator and one needs to be the actual device).

Login with different usernames and start chatting to see the messages being sent and received on both devices in real time.


Summing it up

In case you’re uncertain about certain parts, here is a tutorial for you to bookmark. It walks through all the above steps:


With just these 5 steps, you get access to chat suit features like voice, video & text chat, file sharing, typing indicators, notifications along with advanced features like custom user lists, in built collaboration (whiteboard & whiteboard) and monetisation tools (role based access control, credit deduction, in app monetisation), friend list synchronisation, audit logs and much more.

You can check out all the features here.

CometChat