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.

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

So change rules to as shown below.

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.

Add internet access permission in AndroidManifest.xml file.

The android studio project has following structure.

Android Real Time Chat Application Using Firebase Tutorial 3

Add following code in respective files.

AndroidManifest.xml

rounded_corner1.xml

rounded_corner2.xml

activity_chat.xml

activity_login.xml

activity_register.xml

activity_users.xml

message_area.xml

Chat.java

Login.java

Register.java

UserDetails.java

Users.java

 

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

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.

84 thoughts on “Android Real Time Chat Application Using Firebase Tutorial

  1. nisha

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

    Reply
  2. Devesh

    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

    Reply
  3. mahmoud

    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?

    Reply
    1. Admin Post author

      You can easily add more columns under it. Just make all the columns that I have shown in the image.

      Reply
  4. Arjun

    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

    Reply
  5. Arjun

    Am facing the error like

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

    Reply
  6. Adnan Quraishi

    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

    Reply
    1. Admin Post author

      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://www.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.

      Reply
      1. Adnan Quraishi

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

        Reply
  7. Adnan Quraishi

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

    Reply
  8. Adnan Quraishi

    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

    Reply
  9. Geethanjali

    I would like to know how to delete a particular message in a chat. And also how to clear or delete chat.

    Reply
  10. soumya

    nice tutorial.I have two questions.
    1> how do i create my own user.json file
    2> how do i push that message

    Reply
  11. bayuna

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

    Reply
  12. Atul kumar

    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

    Reply
    1. Admin Post author

      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/

      Reply
  13. Saalem

    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

    Reply
  14. ramgopal

    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

    Reply
  15. Chiranjib

    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.

    Reply
  16. Chiranjib

    can I get notification when new message encounter, and app is in foreground.

    Reply
  17. Neeraj

    Why i need to sign in again again.
    Plz help i dont want to sign in again again.

    Reply
    1. Admin Post author

      I have not added session management in the app, you have to add the feature to keep logged in.

      Reply
  18. suraj kalyankar

    sir which server of firebase you have used is it xmpp server or http server

    Reply
  19. aniket

    i want to send images like whatsapp app with text how can i acheive this

    Reply
  20. Sanjay

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

    Reply
  21. Rohit

    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

    Reply
    1. Admin Post author

      May be you have placed it at wrong location, check it again.

      Reply
      1. Rohit

        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.

        Reply
  22. zubairkhan

    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

    Reply
  23. Lazar

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

    Reply
  24. Somya Tandon

    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!!!

    Reply
  25. Lazar

    How can add notification when user is sending message to other user

    Reply
  26. Somya Tandon

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

    Reply
  27. Deepak

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

    Reply
    1. Admin Post author

      Yes you can, but before that make firebase project in your firebase console.

      Reply
  28. Chitti

    Thanks, It is working perfectly with me…

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

    Reply
  29. chitii

    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.

    Reply
  30. gopala

    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)

    Reply
      1. gopala

        how to link shared preference to firebase db,(hoe does it fetch username and password)

        Reply
  31. tuito

    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

    Reply
  32. wmastersec

    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

    Reply
    1. Admin Post author

      I have shared the link to download the source code. Just check at the end of this tutorial.

      Reply
  33. Abhishek Hule

    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

    Reply
  34. sharath

    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

    Reply
  35. Ankit Kamboj

    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.

    Reply
    1. Admin Post author

      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

      Reply
  36. Abhijeet

    Thank you very much for the tutorial…very useful…and easy to understand.

    Reply
  37. shikhar

    i can send the messages but im not getting them on different mobile…..

    Reply
  38. Roman

    Firebase reference1, reference2;
    gettting error on firebase at chat activity

    Reply
  39. Vora

    Hello,
    I am unable to register /login. i am getting Unexpected response code 401 Error. Please Help

    Reply
  40. sadi harb

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

    Reply
  41. Alok Sain

    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

    Reply
  42. jaka

    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

    Reply
  43. Alok Sain

    How to fetch contact list to show favourite list like whats app..

    Reply
  44. Newbie

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

    Reply

Leave a Reply

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