Real Time Android Chat Application using Firebase

 

Hello Guys. In this tutorial, we will learn how to make and Real time Android Chat Application using Firebase. Now why do we choose Firebase?? Because we don’t have to write database code. Making an Android Chat App using firebase is a piece of cake. You don’t have to maintain a separate database to store all chats. Firebase automatically does it for you.

Real Time Android Chat Application using Firebase

Download Source Code For ChatApp

Following is how our android chat application will look like:chat

How to create chat application in android using android studio

This Android chat will be created in Android Studio. Here we will use volley to get any required data from firebase database in case of login. You can read about how to get data from web using Android Volley. We are using Android Studio because it is very user friendly and one can easily write, update or run code there.

Working of firebase chat app android

In this Firebase Chat App, we will first ask the user to register. If he/she is already registered then he can directly click on the login screen and fill username and password. After logging in, all registered users will be shown and the user can start chatting with anyone. All these user credentials and chat messages will be stored in online Firebase database. Isn’t it amazing ??

Making of Android Chat Application using Firebase

Here we will make separate classes each for login, registration, Users list and Chat. Also separate layout files will be created for each one.

Let’s start making our android chat application.

First of all, create a firebase account. Follow following steps:

  1. Go to Firebase Website firebase.google.com and create a firebase account to start with. Go to Firebase console and Create a New Project by clicking on the “Create New Project” Button as shown below.add_project2.Give the Project name and country you are currently in, Once you are done click on “Create Project” button.create a project3.In the next screen choose “Add Firebase to your Android app” and then add the package details and Debug signing certificate SHA-1 key( This is required if you want to enable certain features like Dynamic Links, Invites, and Google Sign-In etc. otherwise it is an optional field).add_firebase_to_your_android app

4.Get SHA-1 key    [ Gradle -> Chat App(root) -> Tasks -> android -> signingReport (double   click )This will download the google-services.json file. Download it to your computer. We will add it to our android app later.get SHA1 key for chat app

5.In the project’s dashboard. Click on Auth Menu, then in the SIGN-IN METHOD click on Email/Password and enable it.signin method This is required because the default security rules for the Android Firebase allows only authenticated users to read and write.

Then click on the Database tab in the Firebase Menu and copy this link :link collection

Also copy the URL of database. In our case it is [ *–this link–*  /users.json. ]

Exmple: https://chatapp-dc05b.firebaseio.com/users.json

You can check the Rules tab to see or change the security rules for reading and writing on Android Firebase Database. Below figure shows the custom settings.rules

You can change these to true, if you want free unauthenticated access to your Firebase. Once you are done with this, Let’s create our Android chat Application that will connect to Firebase Database we have just created and uses Firebase Authentication that we have enabled in the console.

Creating a New Project

  1. Go to File → New → New Project and enter your Application Name. In our case it is Android Chat App
  2. Enter company domain, this is used to uniquely identify your App’s package worldwide. Remember to use the same package name as used in the firebase console.
  3. Choose project location and minimum SDK and on the next screen choose Empty Activity, since we would be adding most of the code Ourselves. Then Click on Next.
  4. Choose an Activity Name. Make sure Generate Layout File check box is selected, Otherwise we have to generate it ourselves.Then click on Finish.

Gradle will configure your project and resolve the dependencies, Once it is complete proceed for next steps.

Add Permissions and Dependencies in Android Chat Application

  1. After Gradle syncs the project, add the google-services.json file to your project’s app folder as shown below.add json
  2. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml fileAndroidManifest.xml<uses-permission android:name="android.permission.INTERNET"/>ince we Since we are making separate classes for login, chat , registration etc. so add Launcher Activity as Login and register other activities as below in AndroidManifest.xml:
    <activity android:name=".Login">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
    
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Register" />
    <activity android:name=".Users" />
    <activity android:name=".Chat" />

    Your AndroidManifest.xml file look like this:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.andrious.chatapp">
        <uses-permission android:name="android.permission.INTERNET"/>
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".Login">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity android:name=".Register" />
            <activity android:name=".Users" />
            <activity android:name=".Chat" />
        </application>
    
    </manifest>
  3. Next, open your app’s build.gradle and add the following dependencies in the dependencies section and packagingOptions in android section:
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.android.volley:volley:1.0.0'
packagingOptions {
    exclude 'META-INF/DEPENDENCIES.txt'
    exclude 'META-INF/LICENSE.txt'
    exclude 'META-INF/NOTICE.txt'
    exclude 'META-INF/NOTICE'
    exclude 'META-INF/LICENSE'
    exclude 'META-INF/DEPENDENCIES'
    exclude 'META-INF/notice.txt'
    exclude 'META-INF/license.txt'
    exclude 'META-INF/dependencies.txt'
    exclude 'META-INF/LGPL2.1'
}

Your app’s build.gradle look like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.andrious.chatapp"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/notice.txt'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LGPL2.1'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:26.+'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    compile 'com.firebase:firebase-client-android:2.5.2+'
    compile 'com.android.volley:volley:1.0.0'
}
apply plugin: 'com.google.gms.google-services'

 

Layout of Firebase chat app android

As already discussed, we will make separate layouts for login, register and chat screen, so first create a layout file named activit_chat.xml:

activit_chat.xml

<?xml version="1.0" encoding="utf-8"?>
<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:background="#ffffff"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.andrious.chatapp.Chat">
    <ScrollView
        android:layout_width="match_parent"
        android:layout_weight="20"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView">
        <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/layout2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:layout_marginBottom="10dp"
                android:id="@+id/layout1">
            </LinearLayout>
        </RelativeLayout>
    </ScrollView>
    <include
        layout="@layout/message_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_marginTop="5dp"/>
</LinearLayout>

Above is the chat layout where a scrollview is created so that user can easily scroll and see old messages. message_area is included to send chat messages in real time.

Now create layout for login screen. Create activity_login.xml:

activity_login.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.andrious.chatapp.Login"
    android:orientation="vertical"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_marginBottom="20dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username"
        android:inputType="text"
        android:maxLines="1"
        android:hint="enter username"
        android:layout_marginBottom="10dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/password"
        android:inputType="textPassword"
        android:maxLines="1"
        android:hint="enter password"
        android:layout_marginBottom="10dp"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/loginButton"
        android:layout_marginBottom="20dp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click here to register"
        android:textSize="20dp"
        android:gravity="center"
        android:id="@+id/register"/>
</LinearLayout>

Create one for register screen too:

activity_register.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.andrious.chatapp.Register"
    android:orientation="vertical"
    android:gravity="center">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:textSize="30dp"
        android:gravity="center"
        android:layout_marginBottom="20dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/username"
        android:inputType="text"
        android:maxLines="1"
        android:hint="enter username"
        android:layout_marginBottom="10dp"/>
    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/password"
        android:inputType="textPassword"
        android:maxLines="1"
        android:hint="enter password"
        android:layout_marginBottom="10dp"/>
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Register"
        android:id="@+id/registerButton"
        android:layout_marginBottom="20dp"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click here to login"
        android:textSize="20dp"
        android:gravity="center"
        android:id="@+id/login"/>

</LinearLayout>

Create a new layout file named activity_user.xml which will be used to store all registered users in a ListView.

activity_user.xml

<?xml version="1.0" encoding="utf-8"?>
<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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.andrious.chatapp.Users"
    android:orientation="vertical">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="No users found!"
        android:id="@+id/noUsersText"
        android:visibility="gone"/>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/usersList"/>
</LinearLayout>

Create one more layout file for message area where user will write and send a text message:

message_area.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="bottom"
    android:orientation="horizontal">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/border"
        android:orientation="horizontal">
        <EditText
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:textColorHint="#CFD8DC"
            android:gravity="center"
            android:background="@android:color/transparent"
            android:hint="Type a message..."
            android:id="@+id/messageArea"
            android:maxHeight="80dp"
            />
        <ImageView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_weight="4"
            android:padding="4dp"
            android:background="@color/colorPrimary"
            android:src="@android:drawable/ic_menu_send"
            android:id="@+id/sendButton"/>
    </LinearLayout>
</LinearLayout>

Create drowable file to show chat messages in a listView.Create one for send message and  receive message another is design . text_in.xml :

text_in.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list>
<item  xmlns:android="http://schemas.android.com/apk/res/android"
    android:top="1dp"
    android:bottom="1dp">
        <shape
            android:shape="rectangle" >
            <solid android:color="#EEEEEE"/>
            <stroke
                android:width="2dip"
                android:color="#EEEEEE" />
            <corners
                android:bottomLeftRadius="20dp"
                android:bottomRightRadius="20dp"
                android:topLeftRadius="20dp"
                android:topRightRadius="20dp" />
            <!-- If you want to add some padding -->
            <padding
                android:left="15dp"
                android:top="5dp"
                android:right="15dp"
                android:bottom="7dp"    >
            </padding>
        </shape>
    </item>
</layer-list>

 

text_out.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list>
    <item  xmlns:android="http://schemas.android.com/apk/res/android"
        android:top="2dp"
        android:bottom="2dp">
        <shape
            android:shape="rectangle" >
            <solid android:color="#2196F3" />
            <stroke
                android:width="2dip"
                android:color="#2196F3" />
            <corners
                android:bottomLeftRadius="20dp"
                android:bottomRightRadius="20dp"
                android:topLeftRadius="20dp"
                android:topRightRadius="20dp" />
            <!-- If you want to add some padding -->
            <padding
                android:left="15dp"
                android:top="5dp"
                android:right="15dp"
                android:bottom="7dp"    >
            </padding>
        </shape>
    </item>
</layer-list>

border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:radius="0dp"
        />
    <stroke
        android:width="1dip"
        android:color="#555555" />
</shape>

So layout work is finally complete. Now let’s start making it work.

Adding Functionality in Android Chat App

As we have already discussed, in this section we will create separate classes for each of login, register, chat and user data. First of all, create Login.java which is our launcher activity:

Login.java

package com.andrious.chatapp;

/**
 * Created by MD.ISRAFIL MAHMUD on 7/20/2017.
 */

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;

public class Login extends AppCompatActivity {
    TextView registerUser;
    EditText username, password;
    Button loginButton;
    String user, pass;

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

        registerUser = (TextView)findViewById(R.id.register);
        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        loginButton = (Button)findViewById(R.id.loginButton);

        registerUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Login.this, Register.class));
            }
        });
        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user = username.getText().toString();
                pass = password.getText().toString();

                if(user.equals("")){
                    username.setError("can't be blank");
                }
                else if(pass.equals("")){
                    password.setError("can't be blank");
                }
                else{
                    String url = "https://chatapp-dc05b.firebaseio.com/users.json";
                    final ProgressDialog pd = new ProgressDialog(Login.this);
                    pd.setMessage("Loading...");
                    pd.show();

                    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
                        @Override
                        public void onResponse(String s) {
                            if(s.equals("null")){
                                Toast.makeText(Login.this, "user not found", Toast.LENGTH_LONG).show();
                            }
                            else{
                                try {
                                    JSONObject obj = new JSONObject(s);

                                    if(!obj.has(user)){
                                        Toast.makeText(Login.this, "user not found", Toast.LENGTH_LONG).show();
                                    }
                                    else if(obj.getJSONObject(user).getString("password").equals(pass)){
                                        UserDetails.username = user;
                                        UserDetails.password = pass;
                                        startActivity(new Intent(Login.this, Users.class));
                                    }
                                    else {
                                        Toast.makeText(Login.this, "incorrect password", Toast.LENGTH_LONG).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            pd.dismiss();
                        }
                    },new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            System.out.println("" + volleyError);
                            pd.dismiss();
                        }
                    });

                    RequestQueue rQueue = Volley.newRequestQueue(Login.this);
                    rQueue.add(request);
                }
            }
        });
    }
}

As you would have easily guessed, in the above code if a user clicks on register button then second activity will start namely Register Activity through startActivity(new Intent(Login.this, Register.class));. After that an event is waiting for Login button to click. If it clicks then corresponding data will be taken from URL using Volley request StringRequest(Request.Method.GET, url, new Response.Listener(). Here note that url is specific for every user. Yours url will be different. After getting required user and password from URL, It will be passed to class Users. So create a new class named Users.java:

Users.java

package com.andrious.chatapp;

/**
 * Created by MD.ISRAFIL MAHMUD on 7/20/2017.
 */

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Iterator;

public class Users extends AppCompatActivity {
    ListView usersList;
    TextView noUsersText;
    ArrayList<String> al = new ArrayList<>();
    int totalUsers = 0;
    ProgressDialog pd;

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

        usersList = (ListView)findViewById(R.id.usersList);
        noUsersText = (TextView)findViewById(R.id.noUsersText);
        pd = new ProgressDialog(Users.this);
        pd.setMessage("Loading...");
        pd.show();
        String url = "https://chatapp-dc05b.firebaseio.com/users.json";
        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
            @Override
            public void onResponse(String s) {
                doOnSuccess(s);
            }
        },new Response.ErrorListener(){
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println("" + volleyError);
            }
        });
        RequestQueue rQueue = Volley.newRequestQueue(Users.this);
        rQueue.add(request);
        usersList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                UserDetails.chatWith = al.get(position);
                startActivity(new Intent(Users.this, Chat.class));
            }
        });
    }
    public void doOnSuccess(String s){
        try {
            JSONObject obj = new JSONObject(s);

            Iterator i = obj.keys();
            String key = "";

            while(i.hasNext()){
                key = i.next().toString();
                if(!key.equals(UserDetails.username)) {
                    al.add(key);
                }
                totalUsers++;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if(totalUsers <=1){
            noUsersText.setVisibility(View.VISIBLE);
            usersList.setVisibility(View.GONE);
        }
        else{
            noUsersText.setVisibility(View.GONE);
            usersList.setVisibility(View.VISIBLE);
            usersList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, al));
        }
        pd.dismiss();
    }
}

In the above code, we are grabbing data from URL using volley method StringRequest. If it is successful then function doOnSuccess(s) will be called. Here user will be added in ListView if user login is successful. This ListView will contain all users who are logged in so that they can choose whom to chat. On selecting any user from ListView, usersList.setOnItemClickListener will get implemented giving life to Chat activity through startActivity(new Intent(Users.this, Chat.class));. So create following file Chat.java:

Chat.java

package com.andrious.chatapp;

/**
 * Created by MD.ISRAFIL MAHMUD on 7/20/2017.
 */

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import com.firebase.client.ChildEventListener;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


public class Chat extends AppCompatActivity {
    LinearLayout layout;
    RelativeLayout layout_2;
    ImageView sendButton;
    EditText messageArea;
    ScrollView scrollView;
    Firebase reference1, reference2;
    SimpleDateFormat sdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat);
        
        sdf = new SimpleDateFormat("EEE, MMM d 'AT' HH:mm a");
        layout = (LinearLayout) findViewById(R.id.layout1);
        layout_2 = (RelativeLayout)findViewById(R.id.layout2);
        sendButton = (ImageView)findViewById(R.id.sendButton);
        messageArea = (EditText)findViewById(R.id.messageArea);
        scrollView = (ScrollView)findViewById(R.id.scrollView);
        scrollView.fullScroll(View.FOCUS_DOWN);
        Firebase.setAndroidContext(this);
        reference1 = new Firebase("https://chatapp-dc05b.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://chatapp-dc05b.firebaseio.com/messages/" + UserDetails.chatWith + "_" + UserDetails.username);
        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String messageText = messageArea.getText().toString();
                if(!messageText.equals("")){
                    Map<String, String> map = new HashMap<String,String>();
                    String currentDateandTime = sdf.format(new Date());
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    map.put("time", currentDateandTime);
                    reference1.push().setValue(map);
                    reference2.push().setValue(map);
                    messageArea.setText("");
                }
            }
        });
        reference1.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                Map map = dataSnapshot.getValue(Map.class);
                String message = map.get("message").toString();
                String userName = map.get("user").toString();
                String time = map.get("time").toString();

                if(userName.equals(UserDetails.username)){
                    addMessageBox("You " , message,time, 1);
                }
                else{
                    addMessageBox(UserDetails.chatWith , message,time, 2);
                }
            }

            @Override
            public void onChildChanged(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onChildRemoved(DataSnapshot dataSnapshot) {

            }

            @Override
            public void onChildMoved(DataSnapshot dataSnapshot, String s) {

            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }
    public void addMessageBox(String name,String message,String time, int type){

        TextView textmsg = new TextView(Chat.this);
        TextView textname = new TextView(Chat.this);
        TextView texttime = new TextView(Chat.this);

        textname.setText(name);
        textname.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
        textmsg.setText(message);
        texttime.setText(time);
        texttime.setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);

        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        LinearLayout.LayoutParams lp3 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp2.weight = 1.0f;
        if(type == 1) {
            lp1.gravity = Gravity.RIGHT;
            lp2.gravity = Gravity.RIGHT;
            lp3.gravity = Gravity.RIGHT;
            textmsg.setBackgroundResource(R.drawable.text_in);
        }
        else{
            lp1.gravity = Gravity.LEFT;
            lp2.gravity = Gravity.LEFT;
            lp3.gravity = Gravity.LEFT;
            textmsg.setBackgroundResource(R.drawable.text_out);
        }
        textname.setLayoutParams(lp1);
        textmsg.setLayoutParams(lp2);
        texttime.setLayoutParams(lp3);
        layout.addView(textname);
        layout.addView(textmsg);
        layout.addView(texttime);
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
}

In the above class, we have first created two handles of Firebase namely reference1 and reference2. Whenever user clicks on sendButtonsendButton.setOnClickListener will get implemented and required message and user will get pushed into reference1 and reference2 which will be automatically get updated in firebase database. addChildEventListeneris used to receive events about changes in the child locations of a given DatabaseReference ref. So when required mesaage is pushed in reference1, it will call onChildAdded which in turn will call addMessageBox(). Method addMessageBox() is used to insert a new entry into ListView which will be shown as chat messages. Everytime addMessageBox is called a new View will be created whose background will be drawable xml file. Required View will get added in Layout through layout.addView(textView);. So chat message layout gets created .Change all the link.

Example:

"*--paste your database URL--*/users.json"

Finally create a new file named Register.java and add following code.

Register.java

package com.andrious.chatapp;

/**
 * Created by MD.ISRAFIL MAHMUD on 7/20/2017.
 */

import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.firebase.client.Firebase;
import org.json.JSONException;
import org.json.JSONObject;

public class Register extends AppCompatActivity {
    EditText username, password;
    Button registerButton;
    String user, pass;
    TextView login;

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

        username = (EditText)findViewById(R.id.username);
        password = (EditText)findViewById(R.id.password);
        registerButton = (Button)findViewById(R.id.registerButton);
        login = (TextView)findViewById(R.id.login);
        Firebase.setAndroidContext(this);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(Register.this, Login.class));
            }
        });
        registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                user = username.getText().toString();
                pass = password.getText().toString();

                if(user.equals("")){
                    username.setError("can't be blank");
                }
                else if(pass.equals("")){
                    password.setError("can't be blank");
                }
                else if(!user.matches("[A-Za-z0-9]+")){
                    username.setError("only alphabet or number allowed");
                }
                else if(user.length()<5){
                    username.setError("at least 5 characters long");
                }
                else if(pass.length()<5){
                    password.setError("at least 5 characters long");
                }
                else {
                    final ProgressDialog pd = new ProgressDialog(Register.this);
                    pd.setMessage("Loading...");
                    pd.show();
                    String url = "https://chatapp-dc05b.firebaseio.com/users.json";
                    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener<String>(){
                        @Override
                        public void onResponse(String s) {
                            Firebase reference = new Firebase("https://chatapp-dc05b.firebaseio.com/users");
                            if(s.equals("null")) {
                                reference.child(user).child("password").setValue(pass);
                                Toast.makeText(Register.this, "registration successful", Toast.LENGTH_LONG).show();
                            }
                            else {
                                try {
                                    JSONObject obj = new JSONObject(s);

                                    if (!obj.has(user)) {
                                        reference.child(user).child("password").setValue(pass);
                                        Toast.makeText(Register.this, "registration successful", Toast.LENGTH_LONG).show();
                                        Intent i = new Intent(Register.this, Login.class);
                                        startActivity(i);
                                    } else {
                                        Toast.makeText(Register.this, "username already exists", Toast.LENGTH_LONG).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            pd.dismiss();
                        }
                    },new Response.ErrorListener(){
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            System.out.println("" + volleyError );
                            pd.dismiss();
                        }
                    });
                    RequestQueue rQueue = Volley.newRequestQueue(Register.this);
                    rQueue.add(request);
                }
            }
        });
    }
}

Above code in pretty much self explanatory.

Also create following following file to store user data.

UserDetails.java

package com.andrious.chatapp;

/**
 * Created by MD.ISRAFIL MAHMUD on 7/20/2017.
 */

public class UserDetails {
    static String username = "";
    static String password = "";
    static String chatWith = "";
}

Now run it. You will be able to see a Login screen. First register your name and then login. Finally you will be able to chat. You can see demo of this tutorial in the video given at start of tutorial.

So it’s done. We hope above explanation helped you in actually making and learning whole code of Android Chat Application. Please comment if you have any doubt.

27 Comments

  1. Toney Sumlin

    October 11, 2017 at 6:17 pm

    Hi, just wanted to post on the great experience we had with the above campaign. Great customer feedback, improved brand awareness. Would definitely do it again.

  2. CH_AR_Y

    October 26, 2017 at 6:46 am

    app build successfully ,when I’m trying to signup .app CRASHES (unfortunately stopped

  3. Anurag Prerit Samrat

    May 11, 2018 at 11:25 am

    in my Login Activity Toast occur (user not found) but in Register Activity Toast occur registration success

  4. admin

    May 24, 2018 at 5:55 pm

    are you done all the step carefully..please check

  5. Sammy Sample

    May 25, 2018 at 5:33 pm

    I really can’t believe how great this site is. Keep up the good work. I’m going to tell all my friends about this place.

  6. Morris Froberg

    June 4, 2018 at 5:08 am

    hello admin, hello everyone, this is my first visit to this blog and I must say the content on this blog is very nice. I actually love reading such articles but not a lot of webmasters write content like this. thanks for taking your time to write such good content

  7. Nona Moosman

    August 29, 2018 at 5:40 pm

    With thanks! Valuable information!

  8. amrit

    September 22, 2018 at 1:31 pm

    hello admin, sir there is problem in my project pls help me to solve it

  9. amrit

    September 22, 2018 at 1:32 pm

    pls reply soon sir

  10. Date Fat Girls

    February 25, 2019 at 6:02 am

    I enjoy looking through an article that can make men and women think.
    Also, thank you for allowing me to comment!

  11. Funny Bird Playing Drum

    February 25, 2019 at 3:47 pm

    It’s an awesome paragraph designed for all the internet users; they will get advantage from it I am sure.

  12. Funny Oscars Meme

    February 25, 2019 at 8:17 pm

    Hi it’s me, I am also visiting this web page on a
    regular basis, this site is genuinely fastidious and the visitors are genuinely sharing fastidious thoughts.

  13. Sleep With Younger Women

    February 26, 2019 at 11:36 pm

    Very good post! We are linking to this great content on our website.
    Keep up the great writing.

  14. Cute Brunette Cam Girl

    February 27, 2019 at 9:36 am

    Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a
    blog site? The account helped me a acceptable deal.
    I had been a little bit acquainted of this your broadcast offered
    bright clear idea

  15. Hairy Cams

    February 27, 2019 at 10:57 am

    Hello colleagues, how is all, and what you desire to say concerning
    this piece of writing, in my view its actually amazing designed for me.

  16. Hairy Pussy Picture

    February 27, 2019 at 12:15 pm

    These are actually fantastic ideas in regarding blogging.

    You have touched some good points here. Any way keep up wrinting.

  17. cocoppa play mod

    February 28, 2019 at 12:38 am

    Excellent goods from you, man. I have understand your stuff previous to and you’re just too great. I actually like what you have acquired here, certainly like what you are saying and the way in which you say it. You make it entertaining and you still care for to keep it wise. I can not wait to read far more from you. This is actually a terrific web site.

  18. Mpendulo Chiliza

    March 5, 2019 at 5:44 pm

    wow, than you so much

  19. Blonde Cam girls

    March 8, 2019 at 5:09 am

    Very energetic article, I loved that a lot. Will there be a part 2?

  20. Panties Cams

    March 8, 2019 at 9:37 am

    It’s really a nice and helpful piece of information. I’m
    happy that you simply shared this useful info with us. Please keep us informed like
    this. Thank you for sharing.

  21. Squirt Cams

    March 11, 2019 at 12:38 pm

    We’re a bunch of volunteers and opening a new scheme in our community.
    Your site provided us with useful information to work on. You have done an impressive
    process and our entire neighborhood will be grateful to
    you.

  22. çocuk sikici

    April 9, 2019 at 5:54 am

    A big thank you for your blog article.Thanks Again. Want more.

  23. wikidot

    April 9, 2019 at 6:13 pm

    the more i read your blog, i feel you’ve done a very good job with this.

  24. necrophilia sex

    April 10, 2019 at 4:55 am

    I cannot thank you enough for the blog post.Really looking forward to read more. Awesome.

  25. russell brunson clickfunnels

    April 11, 2019 at 10:33 am

    I was excited to uncover this site. I want to to thank you for your time just for this wonderful read!! I definitely really liked every part of it and i also have you book-marked to look at new stuff in your web site.

Leave a Reply