Android Based Chat Application Using Firebase
A mini project report submitted by
B.VINAVATANI (REG NO: URK18CS042)
In partial fulfillment for the award of the degree
of
BACHELOR OF TECHNOLOGY
in
COMPUTER SCIENCE AND ENGINEERING
Under the supervision of
Mrs. T.Mathu, Assistant Professor
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
KARUNYA INSTITUTE OF TECHNOLOGY AND SCIENCES
(Declared as Deemed-to-be-under Sec-3 of the UGC Act, 1956)
Karunya Nagar, Coimbatore - 641 114. INDIA
March 2021
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
BONAFIDE CERTIFICATE
This is to certify that the project report entitled, Android Based Chat Application Using
Firebase is a bonafide record of Mini Project work done during the even semester of the
academic year 2020-2021 by
B.VINAVATANI (REG NO: URK18CS042)
in partial fulfillment of the requirements for the award of the degree of Bachelor of
Technology in Computer Science and Engineering of Karunya Institute of Technology and
Sciences.
Submitted for the Viva Voce held on _________________
Project Coordinator Signature of the Guide
ACKNOWLEDGEMENT
First and foremost, I praise and thank ALMIGTHY GOD whose blessings have
bestowed in me the will power and confidence to carry out my project.
I am grateful to our beloved founders Late. Dr. D.G.S. Dhinakaran, C.A.I.I.B, Ph.D
and Dr. Paul Dhinakaran, M.B.A, Ph.D, for their love and always remembering us in their
prayers.
I extend my thanks to our Vice Chancellor Dr. P. Mannar Jawahar, Ph.D and our
Registrar Dr. Elijah Blessing, M.E., Ph.D, for giving me this opportunity to do the project.
I would like to thank Dr. Prince Arulraj, M.E., Ph.D., Dean, School of Engineering
and Technology for his direction and invaluable support to complete the same.
I would like to place my heart-felt thanks and gratitude to Dr. J. Immanuel John
Raja, M.E., Ph.D., Head of the Department, Computer Science and Engineering for his
encouragement and guidance.
I feel it is a pleasure to be indebted to, Mr. J. Andrew, M.E, (Ph.D.), Assistant
Professor, Department of Computer Science and Engineering and Mrs. T.Mathu for their
invaluable support, advice and encouragement.
I also thank all the staff members of the Department for extending their helping hands
to make this project a successful one.
I would also like to thank all my friends and my parents who have prayed and helped
me during the project work.
ABSTRACT
Communication through internet is becoming vital these days. An online communication
allows the users to communicate with other people in a fast and convenient way. Considering
this, the online communication application must be able share the texts or images or any other
files in a faster way with minimum delay or with no delay. Firebase is one of the platforms
which provide a real-time database and cloud services which allow the developer to make
these applications with ease. Instant messaging can be considered as a platform to maintain
communication. Android provides better platform to develop various applications for instant
messaging compared to other platforms such as IOS. The main objective of this project is to
present a software application for the launching of a real time communication between
operators/users. The system developed on android will enable the users to communicate with
other users through text messages with the help of internet. The system requires both the
device to be connected via internet. This application is based on Android with the backend
provided by Google Firebase.
CONTENTS
Acknowledgement i
Abstract ii
1. Introduction. 6
1.1 Introduction
1.2 Objectives
1.3 Problem Statement
1.4 Scope
1.5 Requirement Specifications
1.6 Modules
2. Analysis and Design. 10
2.1 Existing System
2.2 Proposed System
2.3 Block Diagram
2.4 Project Description
3. Implementation. 16
3.1 Tools used
3.2 Working of the app
4. Test results/ Results. 18
4.1. Testing
4.2. Results
5. Conclusion and Future work 27
References 29
Appendix
32
CHAPTER 1
INTRODUCTION
1.1 Introduction
In the real world the communication plays a very vital role. People have been communicating
with each other through various applications or mediums. In the beginning people
communicated with each other using letters or other sources, as these mediums could take
much time to deliver the content. Cell phones are another medium of communication but the
drawback is for any limited or small message which need to be passed to another user then
phone call is not an ideal way. The developers then looked to implement a text-based
communication which would allow an in instant communication service. Some are Bluetooth
based and some were internet based such as WhatsApp , WeChat and others as cited in [6].
Android is an operating system for mobiles which was developed by Google. This operating
system allows the applications to be used on mobiles. As it was developed by Google,
android users can develop mobile applications and can be sold through android application
stores such as play store.
Firebase is a NoSQL database which makes use of sockets which allows the users to store
and retrieve the data from the database. It also provides the data backup using real time
databases. Firebase cloud is for storing the data such as video, text, pictures building the
infrastructure would be difficult and expensive for a new developer so the firebase provides
the platform of cloud storage as cited in [14].
This project is concerned of a software application for the establishment of a real time
communication services between operators/users. Chat application many-to-many type of
communication system where the users will able to exchange the messages among
themselves. User can create the chatroom according to the requirement or can also join to the
existing chatroom.
1.2 Objectives
The basic goal is to create a system which can create chatroom according to the users and
store the related data at a single place.
To implement the real time chatting application which can allow the user to make instant
group messages by implementing Google firebase cloud and real time databases to store the
data.
The objective of this project is to succeed in creating and developing a fully functional
mobile application that will provide the user all the features of any messenger app on the
market at the moment, but with added features and functionality that are not currently
available on any of the most popular messenger apps. The app will be developed develop
using Android Studio with the intention of making the app available on the Google Play Store
for download and installation, this will users of android smart devices download and use the
app.
1.3 Problem Statement
This project is to create a chat application with a server and users to enable the users
to chat with each other‘s.
To implement complete Online Global Chat System with semantics Analysis using
Firebase Database.
To implement the semantic analysis for the large collected data and process it into the
small sub-modules.
1.4 Scope
The final application will result as a real time communication application which
provides the users to communicate to Insurance Agents with an ease where their
mobile no will be secured.
● The application will have a login page through which the user can register and login
to their account.
Home page of the application contains three fragments CHATS FRIENDS in chats
tab shows the last sent message, friends fragment shows all friends on that fragment
as cited in [9].
● The user can be able to search for the other user.
● User can send and receive text messages
1.5 Requirement Specifications
To run this project on various platforms, we need some hardware and software to
support this project.
Hardware Specification:
Processor: Dual Core
RAM: 512 MB
Memory: 100 MB (minimum)
Software Specification:
Technologies: ANDRIOD, FIREBASE
Database: FIREBASE
Language: JAVA
IDE: ANDRIOD STUDIO
Android Studio is the official IDE for android platform development and is freely available
under the apache license. It is designed specifically for Android development and I am using
it to develop the app, as thus far the app is exclusive to android.
Google Firebase is a mobile platform for helping to develop app, and increase your user base.
It’s made up of features that can be mixed and matched to fit the needs of the user. Most of
the features on Firebase are free to use. I will be using Firebase for app sign in options and
authentication and to maintain a user database.
FIGURE 1: IDE
1.6 Modules:
Login Module
The user must use the valid username and password to sign into the application. The
user must register their credentials to use this application. The application will ask for
a username and password, previously created in the Database.
Firebase Authentication
Firebase Authentication is useful to both developers and the users. Developing and
maintaining sign-in set-up may be a bit difficult and time taking. Firebase provides an
easy API for sign in. This authentication process is to avoid some malpractice.
Chat Module
This module provides an interactive environment for the participants. Here the
participants can share their views and ideas and make decisions on how to complete
the work in a most effective way. After the successful completion of the work, this
module let the users to exit the group.
CHAPTER 2
SYSTEM DESIGN AND ANALYSIS
2.1 Existing System
Most of the internet public messaging, image or files sharing applications are using logic
through which the content that has shared publicly will be collected under one reference or
name. Instagram or Facebook which has an instant image or video sharing feature uses this
kind of mechanism. The algorithm for this logic is to check whether the text posted by the
user contains a special character hash symbol (number sign or pound sign) at the beginning of
it as cited in [11]. The hash symbol is considered as a key and checks whether the name is
already existing or not. If yes then the content posted by the user is shared and shows up to
other users when relevant search requests originates. If the name is new then the room is
created in the database and the remaining mechanism is same as mentioned.
2.2 Proposed System
It is an internet based instant messaging application which provides the user to communicate
with other users in a fast and convenient way. Both the devices must have an active internet
connection for the communication. As a part of day to day life, academic or professional life
users need to send and receive files. Using this application user can communicate with any
user all over the world. In this application we are using Google firebase as the backend to
store the data of the application such as messages, pictures, files and more. User has to
register or sign-in through their respective mail id and can use the services. When the user
sign-in to the application, user can search for another user where the communication is need
to be done. The user can be able to delete the chat after the communication. User can create
their profile according to which other users will be able to identify each other. This
application is designed of android mobile phone users. User can respond to the messages
received by just typing the reply message and press the send button. This application also
provides the user to delete the account. User can also sign-out from the present device and
can sign-in through another.
2.3 Block Diagram
Authentication Diagram
FIGURE 2.1: AUTHENTICATION DIAGRAM
Login or Register Diagram
FIGURE 2.2: LOGIN DIAGRAM
2.4 Project Description
There are certain algorithms which are been used to develop the application, which includes
Authentication: Most of the application requires the identity of the user which will help
making the data of the user safer and more secured in a cloud. Firebase provides backend,
SDK and ready to use libraries which help the developer to provide authentications
effortlessly.
It lets the user to login into the application with a valid email id. It first initializes the
variable sign_in to 1. That means true. The user then enters the email id which is stored in
another variable internally in the database. The email id is then verified and the result is
stored in a variable request_code. If the value of the request_code matches with the value of
the variable if both the values are same then it is considered as the email is valid and the user
sing in to the application. If the values do not match then the signin will not be done and the
task ends.
Send and receive messages: After a successful signin the user can now able to send and
receive the messages shown in Figure 2.3.
FIGURE 2.3: FLOW CHART
The final system will result as a real time communication application which provides the
users to communicate to each other with an ease. The application will have a login page
through which the user can register and login themselves. Home page of the application
contains the previous messages if any. The user can be able to search for the other user. User
can send and receive text messages. The user can create chat rooms and can search for the
content or information. With these chat rooms users can exchange views and information
about various topics. The identity of the user can also be made hidden in these public chat
rooms.
CHAPTER 3
IMPLEMENTATION
3.1 Tools Used
Android Studio
Android Studio is the official integrated development environment for Google's Android
operating system, built on JetBrains' IntelliJ IDEA software and designed specifically for
Android development. It is available for download on Windows, macOS and Linux based
operating systems. It is a Java integrated development environment for software, and
incorporates its code editing and developer tools. Android Studio provides the fastest tools
for building apps on every type of Android device. Android Studio supports all the same
programming languages of IntelliJ (and CLion) e.g. Java, C++, and more with extensions,
such as Go and Android Studio 3.0 or later supports Kotlin and "all Java 7 language features
and a subset of Java 8 language features that vary by platform version.
FIGURE 3.1: IDE
Firebase Realtime Database
The Firebase Realtime Database is a cloud-hosted database. Data is stored as JSON and
synchronized in realtime to every connected client. When you build cross-platform apps with
our iOS, Android, and JavaScript SDKs, all of your clients share one Realtime Database
instance and automatically receive updates with the newest data. The Firebase Realtime
Database lets you build rich, collaborative applications by allowing secure access to the
database directly from client-side code. Data is persisted locally, and even while offline,
realtime events continue to fire, giving the end user a responsive experience. When the device
regains connection, the Realtime Database synchronizes the local data changes with the
remote updates that occurred while the client was offline, merging any conflicts
automatically. The Realtime Database provides a flexible, expression-based rules language,
called Firebase Realtime Database Security Rules, to define how your data should be
structured and when data can be read from or written to. When integrated with Firebase
Authentication, developers can define who has access to what data, and how they can access
it.
FIGURE 3.2: FIREBASE
3.2 Working of the android app
The Front-end of the app is made with the help of Andriod studio. Andriod studio
helps in making custom components and uses them in as many areas we want to use.
This project is concerned of a software application for the establishment of a real time
communication services between operators/users. Chat application many-to-many
type of communication system where the users will able to exchange the messages
among themselves. User can create the chatroom according to the requirement or can
also join to the existing chatroom. It allows us to create minimal and good looking
user interface which is pleasing for the user’s eyes.
The Back-end of the app is made with the help of firebase. Firebase provide users
with great services which help us to make a fully working web-app without writing a
lot of code in the back-end for the app. It provides us integrated authentication, which
can be impended with their built-in functions. It also provides a module for real-time
database where we can store the data for the app. For all services we need to
implement in our app we have to install its dependencies, and integrate it in the app.
The real-time database is super-fast and all changes saved to the database will reflect
in the app immediately.
CHAPTER 4
Test results/Results
4.1 Testing
This test was used to monitor any implications that may arise during the creation of a new
account on the app. The test was carried out by a volunteer tester and resulted in the
successful completion of the create an account task. The app ran smoothly and worked as it
should, the tester had no difficulty during the performance of this task. This leads us to
believe that interface testing has been successful.
Step 1: Tester enters username and password to be used in account setup as shown in Figure
4.1, if it is not recognized in the database, the tester is redirected to register the account.
FIGURE 4.1: LOGIN
Step 2: Tester is redirected to create an account as shown in Figure 4.2 because the
username is not recognised as an existing user.
FIGURE 4.2: REGISTER
Step 3: Tester can check the firebase content where users and messages are being stored
shown in Figure 4.3.
FIGURE 4.3: DATABASE
The app will provide the user with 4 different GUI’s:
1. Login.
2. Register.
3. Registered Users.
4. Main page, send text.
Login Page
Login page or the sign in with username page is where users can sign in using their username
shown in Figure 4.4, users will land on this page when the application is launched if they do
not have an account or have signed out of their last visit. At this point users can sign in, sign
up, or exit the application.
FIGURE 4.4: LOGIN
Register Page
Once a user has entered and username on the launch page Firebase will send the user to the
create an account page if the username is not authenticated in the Firebase database shown in
Figure 4.5. On this page users are prompted to enter their name and password. Users can then
press save and their account setup will be complete.
FIGURE 4.5: REGISTER
Registered Users
Once a user has created an account they can use the sign in page to enter their password and
gain access to the application. The sign in page also offers an option for users to check list of
other users shown in Figure 4.6 and in firebase database we can see all the registered users.
FIGURE 4.6: USERS
Main Page Send Text
On this page users can write, send, receive, and read all text messages from other users
shown in Figure 4.7. This is also where users can read messages displaying information on
other users WIFI network connections.
FIGURE 4.7: CHAT PAGE
4.2 Results
The final system will result as a real time communication application which provides the
users to communicate to each other with an ease. The application will have a login page
through which the user can register and login themselves. Home page of the application
contains the previous messages if any. The user can be able to search for the other user. User
can send and receive text messages. The user can create chat rooms and can search for the
content or information. With these chat rooms users can exchange views and information
about various topics. The identity of the user can also be made hidden in these public chat
rooms.
The final application will result as a real time communication application which provides the
users to communicate with an ease where their mobile will be secured.
The application will have a login page through which the user can register and login to
their account.
Home page of the application contains three fragments CHATS, FRIENDS and chats tab
shows the last sent message , with friends fragment shows all friends on that fragment.
● The user can be able to search for the other user.
● User can send and receive text messages
On completion of this system, we are left with a fully functional communication application
capable of sending messages in real-time and images were also being transferred. The
Firebase services are important in the sense that those tools made the development of this
applications a lot more efficient and lot faster compared to building a traditional server-side
database using a scripting language. The application is user-friendly and intuitive, so using it
is not a difficult task.
CHAPTER 5
Conclusion and Future works
The advantages of the app itself are nothing new, anybody that uses a smart device most
likely has one or more messenger apps on that device. Messenger apps allow users to use free
messaging and calling services once the user can connect to a wireless network, who would
turn down such a service. Their disadvantage of not having a feature like this implemented is
ultimately my ideas advantage, but them having amounted massive popularity over the years
is my apps disadvantage. Do I see an app like mine being able to overthrow a big messenger
like WhatsApp or Facebook Messenger?? Absolutely not! but my app does hold what I
believe to be a key feature that would only make the already immense popularity of those
messenger apps grow even further, while helping to keep people safe and that’s the ultimate
goal, user safety and security as cited in [3].
The system is open to evolve, over time extra features may be added to the system such as
introducing an auto emailing feature as suggested by one of our survey takers. End to end
encryption of messages should be added in the future to keep user conversations safe and
secured. A function for mapping the most recent route of a user where their device made
several Wi-Fi connections could be added to the application to cater for certain users, such as
those who are of special needs but like to maintain some independence. The only limitations
of this project right now are my lack of experience in the field and my limited knowledge of
the overall area of the project.
There is always some place for enhancements in any software application, however good and
efficient the application may be.
Right now, we are dealing with only the instant messaging between the peers. In future the
application may further developed to include some features such as
1. Voice messaging.
2. Group calling
3. Live streaming
4. Messages auto delete after a given time.
5. Personalized message tunes.
6. Authentication
And a messaging application feature which allows the user to create chat room while in
conversation with another user by just sending the chatroom name with the hash symbol at
the beginning.
References
[1] Anon., 2015. Development of a Health Care Assistant App for the Seniors.
International Journal of Applied Science and Engineering, pp. 3-5.
[2] Jianye Liu; Jiankun Yu, Research on Development of Android Applications, 4th
International Conference on Intelligent Networks and Intelligent Systems, 15
December 2011
[3] Abhinav Kathuria et al, Challenges in Android Application Development: A Case
Study, Vol.4 Issue.5, May- 2015, pg. 294-299
[4] Li Ma et al, Research and Development of Mobile Application for Android
Platform, International Journal of Multimedia and Ubiquitous Engineering 9(4):187-
198 • April 2014
[5] Nikhil M. Dongre, Nikhil M. Dongre, Journal of Computer Engineering (IOSR-
JCE), Volume 19, Issue 2, Ver. I (Mar.-Apr. 2017), PP 65-77
[6] Javed Ahmad Shaheen et al, Android OS with its Architecture and Android
Application with Dalvik Virtual Machine Review, International Journal of
Multimedia and Ubiquitous Engineering Vol. 12, No. 7 (2017), pp. 19-30
[7] Sajid Nabi Khan, Ikhlaq Ul Firdous, Review on Android App Security,
International Journal of Advanced Research in Computer Science and Software
Engineering, Volume 7, Issue 4, April 2017
[8] Lazarela Lazareska, Kire Jakimoski et al, Analysis of the Advantages and
Disadvantages of Android and iOS Systems and Converting Applications from
Android to iOS Platform and Vice Versa, American Journal of Software Engineering
and Applications 2017; 6(5): 116-120
[9] Bin Peng et al, The Android Application Development College Challenge, 2012
IEEE 14th International Conference on High Performance Computing and
Communication & 2012 IEEE 9th International Conference on Embedded Software
and Systems, 18 October 2012
[10] Shao Guo-Hong, Application Development Research Based on Android
Platform,2014 7th International Conference on Intelligent Computation Technology
and Automation, 08 January 2015
[11] S Karthick, Android security issues and solutions, 2017 International Conference
on Innovative Mechanisms for Industry Applications (ICIMIA), 13 July 2017
[12] Pravin Auti, Sangam Mahale, Vikram Zanjad, Madhuri Dangat, n.d. An Android
Based Global Chat Application. 4(1), pp. 1-2.
[13] Pravin Auti, Sangam Mahale, Vikram Zanjad, Madhuri Dangat, n.d. An Android
Based Global Chat Application. 4(1).
[14] S, A. K., n.d. Mastering Firebase for Android Development: Build real-time,
scalable, and cloud-enabled Android apps with Firebase. s.l.: s.n
APPENDIX
SOURCE CODE
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>
Chat.java
package com.androidchatapp;
import androidx.appcompat.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 = findViewById(R.id.layout1);
sendButton = findViewById(R.id.sendButton);
messageArea = findViewById(R.id.messageArea);
scrollView = findViewById(R.id.scrollView);
Firebase.setAndroidContext(this);
reference1 = new Firebase("https://androidchatapp-c500f-default-
rtdb.firebaseio.com/messages/" + UserDetails.username + "_" +
UserDetails.chatWith);
reference2 = new Firebase("https://androidchatapp-c500f-default-
rtdb.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<>();
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;
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 androidx.appcompat.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 = findViewById(R.id.register);
username = findViewById(R.id.username);
password = findViewById(R.id.password);
loginButton = 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://androidchatapp-c500f-default-
rtdb.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 androidx.appcompat.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 = findViewById(R.id.username);
password = findViewById(R.id.password);
registerButton = findViewById(R.id.registerButton);
login = 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://androidchatapp-c500f-
default-rtdb.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://androidchatapp-c500f-default-rtdb.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 androidx.appcompat.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 = findViewById(R.id.usersList);
noUsersText = findViewById(R.id.noUsersText);
pd = new ProgressDialog(Users.this);
pd.setMessage("Loading...");
pd.show();
String url = "https://androidchatapp-c500f-default-
rtdb.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();
}