Android Real Time Chat Application Using Firebase Tutorial

In this tutorial you will learn to build an android real time chat application using firebase database.

Before reading this tutorial I hope you are already familiar with basic read and write operations on firebase. If you don’t know then I would recommend you to follow below link to get basic overview about firebase.

Read: https://firebase.google.com/docs/database/android/start/

I have developed a very basic and simple chat app in which user can login and register in the system and can do one to one chat with other users.

Android Real Time Chat Application Using Firebase Tutorial 1

Video Demo

Watch below video to see how the app works.

Android Real Time Chat Application Using Firebase Tutorial

Firebase

Go to firebase console and create a new project.

Link: https://console.firebase.google.com/

Select Database option in left sidebar. The database structure used in this project looks as shown in below image.

Android Real Time Chat Application Using Firebase Tutorial 2

In my case the database base url is https://android-chat-app-e711d.firebaseio.com/. It will be different in your case so make sure to change the url wherever used in the code.

You can access the child in form of json data by just adding .json at the end of parent url. For example in this app I have accessed users data by url https://android-chat-app-e711d.firebaseio.com/users.json.

Read more about it here https://firebase.google.com/docs/reference/rest/database/

Security Rules

By default only authenticated user can access the database. When you will go to Rules tab in firebase console project then it may look like this.

{
  "rules": {
    ".read": "auth != null",
    ".write": "auth != null"
  }
}

When you try to run the app you may get authentication failure error.

So change rules to as shown below.

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

Note: Above security rules will allow anyone to read, write and edit data. That means any user can edit data of any other user. This must not be allowed. So use this security rule only for testing purpose. Don’t use it if you are making the app live in market. To learn more about firebase security rules visit below link.

https://firebase.google.com/docs/database/security/

Android Studio

Create a new android studio project with package name com.androidchatapp

Now add dependency for firebase database and volley in build.gradle (Module: app) file. Add following lines under dependency section and sync the project.

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

Add internet access permission in AndroidManifest.xml file.

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

The android studio project has following structure.

Android Real Time Chat Application Using Firebase Tutorial 3

Add following code in respective files.

AndroidManifest.xml

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

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        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>

rounded_corner1.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#dddddd" />
    <stroke
        android:width="0dip"
        android:color="#dddddd" />
    <corners android:radius="10dip" />
    <padding
        android:bottom="5dip"
        android:left="5dip"
        android:right="5dip"
        android:top="5dip" />
</shape>

rounded_corner2.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#f0f0f0" />
    <stroke
        android:width="0dip"
        android:color="#f0f0f0" />
    <corners android:radius="10dip" />
    <padding
        android:bottom="5dip"
        android:left="5dip"
        android:right="5dip"
        android:top="5dip" />
</shape>

activity_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.androidchatapp.Chat">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_weight="20"
        android:layout_height="wrap_content"
        android:id="@+id/scrollView">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:id="@+id/layout1">

      </LinearLayout>
    </ScrollView>

    <include
        layout="@layout/message_area"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="bottom"
        android:layout_marginTop="5dp"/>
</LinearLayout>

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

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

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

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:background="@color/colorPrimaryDark"
    android:gravity="bottom"
    android:orientation="horizontal">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:textColorHint="#CFD8DC"
        android:textColor="#CFD8DC"
        android:hint="Write 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:src="@android:drawable/ic_menu_send"
        android:id="@+id/sendButton"/>
</LinearLayout>

Chat.java

package com.androidchatapp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
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;
    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);
        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://android-chat-app-e711d.firebaseio.com/messages/" + UserDetails.username + "_" + UserDetails.chatWith);
        reference2 = new Firebase("https://android-chat-app-e711d.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>();
                    map.put("message", messageText);
                    map.put("user", UserDetails.username);
                    reference1.push().setValue(map);
                    reference2.push().setValue(map);
                }
            }
        });

        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 lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        lp.setMargins(0, 0, 0, 10);
        textView.setLayoutParams(lp);

        if(type == 1) {
            textView.setBackgroundResource(R.drawable.rounded_corner1);
        }
        else{
            textView.setBackgroundResource(R.drawable.rounded_corner2);
        }

        layout.addView(textView);
        scrollView.fullScroll(View.FOCUS_DOWN);
    }
}

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 register;
    EditText username, password;
    Button loginButton;
    String user, pass;

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

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

        register.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://android-chat-app-e711d.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);
                }

            }
        });
    }
}

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.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://android-chat-app-e711d.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://android-chat-app-e711d.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();
                                                } 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);
                            }
            }
        });
    }
}

UserDetails.java

package com.androidchatapp;

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

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<String> 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://android-chat-app-e711d.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();
    }
}

 

Screenshots

Android Real Time Chat Application Using Firebase Tutorial 4 Android Real Time Chat Application Using Firebase Tutorial 5

Android Real Time Chat Application Using Firebase Tutorial 6 Android Real Time Chat Application Using Firebase Tutorial 7

Check this article for Top 10 Best Live Chat Software Solutions Compared

You can download the apk and source code from below link.

Apk: http://www.mediafire.com/file/jwurkc69pag2u6w/Android+Chat+App_V1.0.apk

Source Code: http://www.mediafire.com/file/djl5s58sbw5kpma/AndroidChatApp.rar 

Feel free to ask your queries by commenting below.

132 thoughts on “Android Real Time Chat Application Using Firebase Tutorial”

  1. I want your help for my final year projetc…and the question is how to fetch active process in android phone to database

  2. registered but cant log in….. user not found error

    W/EGL_emulation: eglSurfaceAttrib not implemented
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e453dc0, error=EGL_SUCCESS
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa1932470
    W/EGL_emulation: eglSurfaceAttrib not implemented
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e453dc0, error=EGL_SUCCESS
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0xa19309c0
    V/FA: Activity paused, time: 1284458
    V/FA: onActivityCreated
    V/FA: Activity resumed, time: 1284528
    W/EGL_emulation: eglSurfaceAttrib not implemented
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9e453f20, error=EGL_SUCCESS
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9fdf8070
    D/InputEventConsistencyVerifier: KeyEvent: ACTION_UP but key was not down.
    in android.support.v7.widget.AppCompatEditText{26e9ba7 VFED..CL. .F….ID 42,746-1038,864 #7f0b005e app:id/password}
    0: sent at 1291504000000, KeyEvent { action=ACTION_UP, keyCode=KEYCODE_TAB, scanCode=15, metaState=0, flags=0x8, repeatCount=0, eventTime=1291504, downTime=1291504, deviceId=0, source=0x101 }
    W/EGL_emulation: eglSurfaceAttrib not implemented
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9ec14de0, error=EGL_SUCCESS
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9fdf8230
    W/EGL_emulation: eglSurfaceAttrib not implemented
    W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0x9ec14de0, error=EGL_SUCCESS
    E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9fdf8230

  3. hello,
    My application database in firebase does not look like yours i have only one column with the app name because of this am not able to signin, how to change it to look like users with messages and users column?

  4. Could you please solve this error while running the project. The error is shown below

    Error:Execution failed for task ‘:app:transformResourcesWithMergeJavaResForDebug’.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
    File1: C:\Users\Arjun\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-databind\2.2.2\3c8f6018eaa72d43b261181e801e6f8676c16ef6\jackson-databind-2.2.2.jar
    File2: C:\Users\Arjun\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-annotations\2.2.2\285cb9c666f0f0f3dd8a1be04e1f457eb7b15113\jackson-annotations-2.2.2.jar
    File3: C:\Users\Arjun\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-core\2.2.2\d20be6a5ddd6f8cfd36ebf6dea329873a1c41f1b\jackson-core-2.2.2.jar

  5. Am facing the error like

    “Error:Failed to capture snapshot of output files for task ‘transformClassesWithDexForDebug’ during up-to-date check.”

    1. converter-jackson-2.0.2.jar
      jackson-annotations-2.7.0.jar
      jackson-core-2.7.2.jar
      jackson-databind-2.7.2.jar

  6. hello neeraj Your code works great , I appreciate you for this nice tutorial , it working perfect with me , but I need your help , I am trying to upload camera pictures to firebase database in base64 string format and other user can get that string and decode it to get to its bitmap ,

    My question is how we will add the image thumbnail in the messagebox ? and only add the image thumbnail when user selects the image and confirms to upload .

    I tried some codes but either empty imageview is sent with every message , or not shown.
    can you provide any simple method which we provide image bitmap and it adds the image view in messagebox and starts uploading , and other peer can receive the thumbnail in messagebox and downloads it . any help would be much appreciated , thanks

    1. 1. First capture image using camera, follow this tutorial http://www.viralandroid.com/2015/12/how-to-capture-image-from-android-camera-and-display-it-programmatically.html

      2. Now show a dialog, if user confirms then add the image dynamically to the chat box, follow this tutorial http://stackoverflow.com/questions/14002996/add-imageview-dynamically-to-view

      3. Convert the bitmap image to base64 and send it to firebase to save it, for converting bitmap to image follow this tutorial http://thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

      4. Follow the reverse process to get image at receiver end.

      I hope this will help.

      1. This works thanks neeraj i have succesfully achieved it . your tutorial is really helpful for learning firebase . Thanks a lot.

  7. How to add ImageView in messagebox for uploading and other peer for downloading ? while using base64 to encode image and storing to firebase databse?

  8. Neeraj if want to block certain user , how can we achieve that . i think a flag should be put in firebase database and on the basis of flag we can verify the user is blocked or not and then display other to list . or is there any other better solution for this in your mind . kindly do share here . Thanks

  9. that the string url “String url = “https://android-chat-app-e711d.firebaseio.com/users.json”;” etc, use my firebase url right??

  10. String url = “https://chatapplication-28729.firebaseio.com/users.json”;
    I use above url for my project but i get this IO Exception

    In Adroid version 18
    com.android.volley.NoConnectionError: java.io.IOException: No authentication challenges found .

    In Adroid version 22
    E/Volley: [5512] BasicNetwork.performRequest: Unexpected response code 401 for https://chatapplication-28729.firebaseio.com/users.json

    System.out: com.android.volley.AuthFailureError

    1. By default authentication is required to use firebase database. When you will go to Rules section in your firebase console project, it may look as shown below.
      {
      "rules": {
      ".read": "auth != null",
      ".write": "auth != null"
      }
      }

      Just change it to.

      {
      "rules": {
      ".read": true,
      ".write": true
      }
      }

      This rule is for development purpose only. If you keep these rules when your chat is live then anyone can read, write and edit data, and that is not good. A user should be allowed to edit its own chat messages only. Learn more about rules at below link.
      https://firebase.google.com/docs/database/security/

  11. Can u plz help me with the below errors

    Error:(30, 17) No resource found that matches the given name (at ‘layout’ with value ‘@layout/message_area’).
    Error:(30, 17) No resource found that matches the given name (at ‘layout’ with value ‘@layout/message_area’).
    C:\Users\Acer\AndroidStudioProjects\AndroidChatApp\app\src\main\res\layout\activity_chat.xml
    C:\Users\Acer\AndroidStudioProjects\AndroidChatApp\app\build\intermediates\res\merged\debug\layout\activity_chat.xml
    Error:Execution failed for task ‘:app:processDebugResources’.
    > com.android.ide.common.process.ProcessException: Failed to execute aapt

  12. ha can you help here we are getting list of user i want only one user.that user is common for every user is it possible

  13. Thank u for your tutorial,its very informative and useful.
    I want more help from you ….
    Can I get notification when message receive, if yes then how please help

    Thank you.

  14. Hello, actually I am new in Firebase. I didn’t get these following lines. Will you please explain.

    Firebase.setAndroidContext(this);

    reference1 = new Firebase(“https://android-chat-app-e711d.firebaseio.com/messages/” + UserDetails.username + “_” + UserDetails.chatWith);

    reference2 = new Firebase(“https://android-chat-app-e711d.firebaseio.com/messages/” + UserDetails.chatWith + “_” + UserDetails.username);

  15. Hello sir,
    I have added all things in my project and wverything is working fine but It says GOOGLE-SERVICES.JSON is not found, but i have already pasted it in app folder.what to do
    please reply

      1. Hello sir,
        Actually At first i tried to copy paste all of your code and changed the url for the firebase only and no any other changes but after that it started firing me unknown errors.So i am unable to run the project.
        But soon after I just imported all of your project and started to configure with my firebase url.but it also didn’t worked.I nedd your help it’s urgent for me.

  16. Error:Execution failed for task ‘:app:transformResourcesWithMergeJavaResForDebug’.
    > com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK META-INF/LICENSE
    File1: C:\Users\ctadmin\Desktop\CHAT\app\libs\jackson-annotations-2.9.0.pr2.jar
    File2: C:\Users\ctadmin\Desktop\CHAT\app\libs\jackson-core-2.9.0.pr2.jar
    File3: C:\Users\ctadmin\Desktop\CHAT\app\libs\jackson-databind-2.9.0.pr2.jar
    File4: C:\Users\ctadmin\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-annotations\2.2.2\285cb9c666f0f0f3dd8a1be04e1f457eb7b15113\jackson-annotations-2.2.2.jar
    File5: C:\Users\ctadmin\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-databind\2.2.2\3c8f6018eaa72d43b261181e801e6f8676c16ef6\jackson-databind-2.2.2.jar
    File6: C:\Users\ctadmin\.gradle\caches\modules-2\files-2.1\com.fasterxml.jackson.core\jackson-core\2.2.2\d20be6a5ddd6f8cfd36ebf6dea329873a1c41f1b\jackson-core-2.2.2.jar

    HOW TO SOLVE THIS TYPE OF ERROR

  17. 03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: org.json.JSONException: Value users of type java.lang.String cannot be converted to JSONObject
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at org.json.JSONObject.(JSONObject.java:160)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at org.json.JSONObject.(JSONObject.java:173)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at com.androidchatapp.Register$2$1.onResponse(Register.java:82)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at com.androidchatapp.Register$2$1.onResponse(Register.java:72)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:60)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:30)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at android.os.Handler.handleCallback(Handler.java:751)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at android.os.Handler.dispatchMessage(Handler.java:95)
    03-31 12:28:35.465 18302-18302/com.androidchatapp W/System.err: at android.os.Looper.loop(Looper.java:154)
    03-31 12:28:35.466 18302-18302/com.androidchatapp W/System.err: at android.app.ActivityThread.main(ActivityThread.java:6119)
    03-31 12:28:35.466 18302-18302/com.androidchatapp W/System.err: at java.lang.reflect.Method.invoke(Native Method)
    03-31 12:28:35.466 18302-18302/com.androidchatapp W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    03-31 12:28:35.466 18302-18302/com.androidchatapp W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

    i cant create columns message and users ( asiking me to put value) ?

  18. sir how can we add date and time for users who are present as well as how can we add notification when user sends a msg to other msg….plz help me out!!!

  19. how can i add date when user is sending msg…as there is no text view to find the text…plz help me!!!

  20. sir i how will i connect it on my server ..please help me ….can i replace your given urls into my server urls..

  21. Thanks, It is working perfectly with me…

    Can u help me send the notifications when we sending the message to appropriate user.

  22. Thanks for the tutorial, it is working fine,

    How can i send notifications (I use fire base console) without using firebase console please help me.. i am new to the firebase.

  23. when we run the app again ,instead of login page again how can we check for last login(the person who login from the device last time his chat page should open automatically)

  24. Sir, will you lease tell me how to create users.json. Using your URL’s COde works perfectly if i change URL with my APPs URL nothing happens. I’m Unable to make changes in database . Please share step by step information for getting users.json

  25. Thank your for great post
    I am beginner to android studio and I had a problem with gradle
    facing this issue :
    Error:(3, 1) A problem occurred evaluating project ‘:app’.
    > Could not find method android() for arguments [build_1lbmbk1vbk1417qf10t4flwtg$_run_closure1@21a82f79] on project ‘:app’.
    i tried a lot of post like this http://stackoverflow.com/questions/40012866/could-not-find-method-android-for-arguments-in-android-studio-project
    but but still not fixed with me
    could you please show me you
    build.gradle (Module: app) file
    and the top level one also build.gradle(Project )file

    please reply I’m stuck

  26. how to implement notifications without using any external servers ….Actually in FCM without using using external servers we can implement notifications.so can u pleaqse help me out with this

  27. Great!!! nice tutorial….I have one question that how to dispaly the user’s name along with their profile photo in listview. Can u pls help me

  28. I have implemented single user chat using your code. It is working fine. Thanks for that. Now, I wan to implement group chat. How can i achieve this functionality? A database schema would be helpful.

    1. It may look like this..

      Chat_App
      *Messages
      -user1
      -hi friends
      -user1
      -how are you guys?
      -user2
      -i am fine
      -user3
      -i am also fine
      -user2
      -lets meet somewhere today
      *Users
      -user1
      -user2
      -user3

  29. How can I connect the VIA control panel to the application or change the control panel currently in use?

  30. Hy,
    Please tell me can i implement login and register with my own web server i don’t want to login and register with firebase and is this possible i login with my own server and when i open chat activity function then firebase login was not show

  31. this not tutorial, u must fix this tutorial.. this code cant run many bugs on compile problem on jakson i dont know how fix it, and i read comment now im confused

  32. Hey i am newbie to firebase. Can u tell me how to create users.json on firebase server because it also asks for value.

    1. Yes I know, its for demonstration purpose only, one should not used it in real world app. Proper access rules should be applied.

  33. Hi!! i need help for how to fetch list of all user’s username while i am authenticating with email and password?

    1. how you manage to run i am getting error in

      “https://android-chat-app-e711d.firebaseio.com/users.json”;

      this line showing no . or special character allowed in firebase path
      can you pls tell how to over get from this line of error

  34. I am not able to register. i have checked by giving Toast that After
    StringRequest request = new StringRequest(Request.Method.GET, url, new Response.Listener()

    it’s not workimg. Toast inside the above method is not working. plz help

  35. hey man. i follow your tutorial. this a good tutorial thaks man. but my app not show 2 chat. but 1 chat from user. not every body. what u have a solution

  36. Akansh Karthik Nair

    Thank you for this wonderful solution given by you. You really saved hours of my day today.
    Thank you again

    1. Actually StringRequest() is method of volley library, we are using it to fetch data from internet. The data can be string or json string. Later on we are parsing the json string using JsonObject, see this line JSONObject obj = new JSONObject(s);

  37. Muhammad Irteza Anwar

    Sir its a nice tutorial but can you please tell is there group chat feature present in this app.If not.kindly upload tutorial for group chat also.

  38. hi sir
    this tutorial is very help ful but my problem is that how to show users with name and password.
    here just show name.
    plz help me

  39. Sir
    when i change the uri and put uri of my project and replaced all uri in all class
    and when i register nothing happen
    why my uri not work like yours pls help me

  40. Sir, can we with out registered user in fcm can we start chatting because i have particular user id come from our web server ? we can use only chat class for start one to one chating.?

  41. I’m able to message but each time it sends messages it returns to the user list page.How can I resolve the issue?Tried many ways but stuck there.

  42. Jayaraj Chanku

    Hi Neeraj,
    Awesome tutorial. Thanks for sharing this.Like your other articles, this is also helpful in the development of knowledge and experiences.

  43. Nice video sir,helped a lot
    but it shows registration is successfull ,still it is not saving in the firebase database,plz tell what shd i do for this sir

  44. Dear Neeraj Mishra thank you very much for developing such a nce and informative one to one chat tutorial with demo.

  45. @Lazar org.json.JSONException: Value users of type java.lang.String cannot be converted to JSONObject How did u solve this problem?

  46. Thanks for awesome tutorial
    But I have doubt that how to implement chat pagination in your url please help me if it is possible

  47. In my firebase database seen entry but in applicatioon i can’t seen msg which i wrote from one user to another user plz help me

  48. Getting error in

    “https://android-chat-app-e711d.firebaseio.com/users.json”;

    this line showing no . or special character allowed in firebase path pls help

  49. I login new user but old user send msg to new user at that time old user dont show msgs…what can i do?new user show the mesaages.

Leave a Comment

Your email address will not be published. Required fields are marked *