Android – How to create chat application?

In this tutorial, I will show how to create very basic chat application. This tutorial contains step by step tutorial how to do it. So let’s start!

Step 1: First of all, import Pubnub library. In order to import, open gradle.build file in your Android Studio. Add following dependency to your dependencies:

compile 'com.pubnub:pubnub-android:3.7.5'

after adding your dependencies should look something like this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.2.1'
    compile 'com.pubnub:pubnub-android:3.7.5'
}

Now from top menu go to Tools->Android->Sync Project with grade files.

Step 2: Add permission to use Internet connection. For this purpose, open AndroidManifest.xml from manifests folder. And add following permission usage:

<uses-permission android:name="android.permission.INTERNET" />

After changing AndroidManifest.xml, it should look something like this:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="net.joerichard.chatexample" >

    <uses-permission android:name="android.permission.INTERNET" />

    <application
       android:allowBackup="true"
       android:icon="@mipmap/ic_launcher"
       android:label="@string/app_name"
       android:theme="@style/AppTheme" >
        <activity
           android:name=".MainActivity"
           android:label="@string/app_name" >
        </activity>
        <activity
           android:name=".NameActivity"
           android:label="@string/title_activity_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Step 3: Let’s create NameActivity. This activity will be open on application launch and will ask user his/her name.
activity_name.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context="net.joerichard.chatexample.NameActivity"
   android:orientation="vertical">

    <EditText android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/etName"
       android:hint="Enter name"/>

    <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/bSaveName"
       android:text="Let's chat!"/>

</LinearLayout>

NameActivity.java

public class NameActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_name);

        final EditText etName = (EditText) findViewById(R.id.etName);

        Button bSaveName = (Button) findViewById(R.id.bSaveName);
        bSaveName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(NameActivity.this, MainActivity.class);
                intent.putExtra("name", etName.getText().toString());
                startActivity(intent);
            }
        });
    }

}

Step 4: go to www.pubnub.com and register as developer. You will get publish key and subscribe key. You will need them in Step 5 in MainActivity.

pubnub

Step 5: Create main Activity. In this activity, there will be 1 EditText to get message, 1 Button to send, 1 TextView inside ScrollView to show messages. ScrollView to make TextView scrollable.

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
   android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
   android:orientation="vertical">

    <EditText android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Enter message"
       android:id="@+id/etMessage"/>

    <Button
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:id="@+id/bSend"
       android:text="Send"/>

    <ScrollView
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:id="@+id/svMessages">

        <TextView
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:id="@+id/tvMessages"/>

    </ScrollView>



</LinearLayout>

MainActivity.java: here you will use your publish key and subscribe key

public class MainActivity extends AppCompatActivity {

    // this stringbuilder will hold messages
    static StringBuilder messages = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final String name = getIntent().getStringExtra("name");

        //register here:http://www.pubnub.com
        //1.get publish key
        //2.get subscribe key
        final Pubnub pubnub = new Pubnub("YOUR_PUBLISH_KEY", "YOUR_SUBSCRIBER_KEY");


        // subscribe to channel: android_club
        // you can set any channel you like
        try {
            pubnub.subscribe("android_club", new Callback() {
                public void successCallback(String channel, Object message) {
                    // this will be called each time, when android_club subsriber get message
                    showMessage(message.toString());
                }

                public void errorCallback(String channel, PubnubError error) {
                }
            });
        } catch (PubnubException e) {
            e.printStackTrace();
        }

        // button to send message
        Button bSend = (Button) findViewById(R.id.bSend);
        bSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Callback callback = new Callback() {
                    public void successCallback(String channel, Object response) {
                    }
                    public void errorCallback(String channel, PubnubError error) {
                    }
                };

                // text will taken from this EditText
                EditText etMessage = (EditText) findViewById(R.id.etMessage);
                // Okey, let's publish(send) message
                pubnub.publish("android_club", name+":"+etMessage.getText().toString(), callback);
                //hey you, let's clean EditText after using
                etMessage.setText("");
            }
        });
    }

    private void showMessage(final String message) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                // okey, we know it is better to save this to DB
                // if you explain how to connect to DB, beginner kill you!
                // that's why let's do it in easy(do not say wrong! I said it is not wrong!)
                messages.append(message);
                messages.append("\n");

                // let's set all text to text view
                TextView tvMessages = (TextView) findViewById(R.id.tvMessages);
                // yes, each time!
                tvMessages.setText(messages.toString());

                // let's scroll to down, down, down......
                ScrollView svMessages = (ScrollView) findViewById(R.id.svMessages);
                svMessages.fullScroll(View.FOCUS_DOWN);
            }
        });

    }

}

Step 6: Let’s run application!
ChatExampleScreenshot

Download apk here
Download source code here – ChatExampleNoApiKeys