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

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.

130 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 https://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.

      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 [[email protected]] 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. 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.

    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 *