Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Real Time Android Chat Application using Firebase Tutorial

Android Chat App Tutorial 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. You can see demo of this tutorial below:

You can download full code of tutorial below:

Following is how our Android Chat Application will look like:

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.
  2. Give the Project name and country you are currently in, Once you are done click on “Create Project” button.
  3. 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). If you are not sure how to generate SHA-1 fingerprint see the following tutorial Adding Google Login to Android Apps under the heading Generate SHA-1 fingerprint
  4. This will download the google-services.json file. Download it to your computer. We will add it to our android app later.

  5. In the project’s dashboard. Click on Auth Menu, then in the SIGN-IN METHOD click on Email/Password and enable it.

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.

It shows the root of the JSON tree, we would be adding a child node called listItems and then will add each item under it. When we add data to the JSON tree, it becomes a new node in the existing JSON structure with an associated key.

Also copy the URL of database. In our case it is https://androidchatapp-76776.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 default settings.

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.
  2. Since we need to connect to the Network add the Internet permission in AndroidManifest.xml file.
  3. AndroidManifest.xml

    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:

    
                
  4. Next, open your app’s build.gradle and add the following dependencies in the dependencies section:
  5. build.gradle

        compile 'com.firebase:firebase-client-android:2.5.2+'
        compile 'com.android.volley:volley:1.0.0'
    

Above dependencies are self-explanatory.

Layout of Firebase chat app android

We would suggest you to please go through our tutorial of Android Chat Bubble Layout with 9 patch Image using ListView to get better grasp on 9-path image and this chat layout.
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

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



    

Create one for register screen too:

activity_register.xml



    

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

activity_user.xml

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

message_area.xml

We will use 9 patch Image to show chat messages in a listView (This ListView is different from what we just made in above layout). We would suggest you to go through our tutorial of Android Chat Bubble Layout with 9 patch Image using ListView. Here we have taught how to make a Chat Bubble layout. We will use that info in this tutorial.

As suggested above, download following two images and save it in drawable folder (at path …/AndroidChatApplication/app/src/main/res/drawable/)

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.androidchatapp;

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://androidchatapp-76776.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(){
                        @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.androidchatapp;

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 al = new ArrayList();
    int totalUsers = 0;
    ProgressDialog pd;

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

        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://androidchatapp-76776.firebaseio.com/users.json";

        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener(){
            @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 (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.androidchatapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
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.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;

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

        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);

        Firebase.setAndroidContext(this);
        reference1 = new Firebase("https://androidchatapp-76776.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://androidchatapp-76776.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 map = new HashMap();
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    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();

                if(userName.equals(UserDetails.username)){
                    addMessageBox("You:-\n" + message, 1);
                }
                else{
                    addMessageBox(UserDetails.chatWith + ":-\n" + message, 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 message, int type){
        TextView textView = new TextView(Chat.this);
        textView.setText(message);

        LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp2.weight = 1.0f;

        if(type == 1) {
            lp2.gravity = Gravity.LEFT;
            textView.setBackgroundResource(R.drawable.bubble_in);
        }
        else{
            lp2.gravity = Gravity.RIGHT;
            textView.setBackgroundResource(R.drawable.bubble_out);
        }
        textView.setLayoutParams(lp2);
        layout.addView(textView);
        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 sendButton sendButton.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 9-patch image which we downloaded at the start of tutorial. Required View will get added in Layout through layout.addView(textView);. So chat message layout gets created.

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

Register.java

package com.androidchatapp;

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 al = new ArrayList();
    int totalUsers = 0;
    ProgressDialog pd;

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

        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://androidchatapp-76776.firebaseio.com/users.json";

        StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener(){
            @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 (this, android.R.layout.simple_list_item_1, al));
        }

        pd.dismiss();
    }
}

Above code in pretty much self explanatory.

Also create following following file to store user data.

UserDetails.java

package com.androidchatapp;

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.

What’s Next ??

After this, you can try making an App like WhatsApp.
Till then stay tuned for more tutorials.. and Don’t forget to subscribe our blog for latest android tutorials. Also do Like our Facebook Page or Add us on Twitter.

To download the full code for the Android Chat Application using the android studio, Click on the Download Now link below.


The post Real Time Android Chat Application using Firebase Tutorial appeared first on Android Tutorial Point.



This post first appeared on Android Tutorial Point, please read the originial post: here

Share the post

Real Time Android Chat Application using Firebase Tutorial

×

Subscribe to Android Tutorial Point

Get updates delivered right to your inbox!

Thank you for your subscription

×