How to Create Chat Application using Firebase in Android
Hello friends, in this tutorial I am going to share with you How to create chat Application using Firebase. Before starting the tutorial we have to know little About Firebase. It is a Cloud Service Provider and Backend service company based on California . This is best alternative to parse for new App for hosting as we know parse is going to retire soon. Another great importance of Firebase is it works also in offline, though in terms of performance Parse works better with large relationship base Database. But another drawback of Firebase is does not support push notification. Let’s Checkout How to create simple Chat Application using Firebase.
Prerequisites:
- JDK 8.0 or above
- Android Studio 2.0
First go to
- Firebase website
- Sign Up with Google Account
- Create an App by giving available name.
- Navigate to API Docs.
- From Android Option go to Android Quickstart .
Now in Android Studio
- Create a New Android Studio project name MChat.
- select minimum API level 16 so it will run maximum of Android device that are Active on google Play then click next.
- select Blank Activity and your Activity name is MainActivity click next > click finish.
- To install the library inside Android Studio, you have to declare it as dependency in your
build.gradle
file:
dependencies {
...
compile 'com.firebase:firebase-client-android:2.5.2+'
}
...
compile 'com.firebase:firebase-client-android:2.5.2+'
}
android{
…
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
}
…
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
}
Now Sync your project in Android studio .
5. Create a new Class name ChatLife.java and write the following code inside it .
public class ChatLife extends Application{
private static final String TAG = "ChatLife";
@Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
}
}
private static final String TAG = "ChatLife";
@Override
public void onCreate() {
super.onCreate();
Firebase.setAndroidContext(this);
}
}
6. Create new Class MessageSource.java . Write the following code inside it
public class MessageSource {
private static final Firebase sRef = new Firebase("YOUR APP URL");
private static SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddmmss");
private static final String TAG = "MessageDataSource";
private static final String COLUMN_TEXT = "text";
private static final String COLUMN_SENDER = "sender";
public static void saveMessage(Message message, String convoId){
Date date = message.getmDate();
String key = sDateFormat.format(date);
HashMap<String, String> msg = new HashMap<>();
msg.put(COLUMN_TEXT, message.getmText());
msg.put(COLUMN_SENDER,"Barun");
sRef.child(convoId).child(key).setValue(msg);
}
public static MessagesListener addMessagesListener(String convoId, final MessagesCallbacks callbacks){
MessagesListener listener = new MessagesListener(callbacks);
sRef.child(convoId).addChildEventListener(listener);
return listener;
}
public static void stop(MessagesListener listener){
sRef.removeEventListener(listener);
}
public static class MessagesListener implements ChildEventListener {
private MessagesCallbacks callbacks;
MessagesListener(MessagesCallbacks callbacks){
this.callbacks = callbacks;
}
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
HashMap<String,String> msg = (HashMap)dataSnapshot.getValue();
Message message = new Message();
message.setmSender(msg.get(COLUMN_SENDER));
message.setmText(msg.get(COLUMN_TEXT));
try {
message.setmDate(sDateFormat.parse(dataSnapshot.getKey()));
}catch (Exception e){
Log.d(TAG, "Couldn't parse date"+e);
}
if(callbacks != null){
callbacks.onMessageAdded(message);
}
}
@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 interface MessagesCallbacks{
public void onMessageAdded(Message message);
}
}
7.Create a new Class named Message.java and add the following code inside it
public class Message {
private String mtext ;
private String mSender;
private Date mDate;
public Date getmDate(){
return mDate;
}
public void setmDate(Date mDate){
this.mDate = mDate;
}
public String getmSender(){
return mSender;
}
public void setmSender(String mSender){
this.mSender = mSender;
}
public String getmText(){
return mtext;
}
public void setmText(String mtext){
this.mtext = mtext;
}
}
private String mtext ;
private String mSender;
private Date mDate;
public Date getmDate(){
return mDate;
}
public void setmDate(Date mDate){
this.mDate = mDate;
}
public String getmSender(){
return mSender;
}
public void setmSender(String mSender){
this.mSender = mSender;
}
public String getmText(){
return mtext;
}
public void setmText(String mtext){
this.mtext = mtext;
}
}
public class MainActivity extends ActionBarActivity implementsView.OnClickListener,MessageSource.MessagesCallbacks{
public static final String USER_EXTRA = "USER";
public static final String TAG = "ChatActivity";
private ArrayList<Message> mMessages;
private MessagesAdapter mAdapter;
private String mRecipient;
private ListView mListView;
private Date mLastMessageDate = new Date();
private String mConvoId;
private MessageSource.MessagesListener mListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecipient = "Rohit";
mListView = (ListView)findViewById(R.id.message_list);
mMessages = new ArrayList<>();
mAdapter = new MessagesAdapter(mMessages);
mListView.setAdapter(mAdapter);
setTitle(mRecipient);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button sendMessage = (Button)findViewById(R.id.send_message);
sendMessage.setOnClickListener(this);
String[] ids = {"Barun","-", "Rohit"};
Arrays.sort(ids);
mConvoId = ids[0]+ids[1]+ids[2];
mListener = MessageSource.addMessagesListener(mConvoId, this);
}
public void onClick(View v) {
EditText newMessageView = (EditText)findViewById(R.id.new_message);
String newMessage = newMessageView.getText().toString();
newMessageView.setText("");
Message msg = new Message();
msg.setmDate(new Date());
msg.setmText(newMessage);
msg.setmSender("Rohit");
MessageSource.saveMessage(msg, mConvoId);
}
@Override
public void onMessageAdded(Message message) {
mMessages.add(message);
mAdapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
MessageSource.stop(mListener);
}
private class MessagesAdapter extends ArrayAdapter<Message> {
MessagesAdapter(ArrayList<Message> messages){
super(MainActivity.this, R.layout.item, R.id.msg, messages);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
Message message = getItem(position);
TextView nameView = (TextView)convertView.findViewById(R.id.msg);
nameView.setText(message.getmText());
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)nameView.getLayoutParams();
int sdk = Build.VERSION.SDK_INT;
if (message.getmSender().equals("Rohit")){
if (sdk >= Build.VERSION_CODES.JELLY_BEAN) {
nameView.setBackground(getDrawable(R.drawable.bubble_right_green));
} else{
nameView.setBackgroundDrawable(getDrawable(R.drawable.bubble_right_green));
}
layoutParams.gravity = Gravity.RIGHT;
}else{
if (sdk >= Build.VERSION_CODES.JELLY_BEAN) {
nameView.setBackground(getDrawable(R.drawable.bubble_left_gray));
} else{
nameView.setBackgroundDrawable(getDrawable(R.drawable.bubble_left_gray));
}
layoutParams.gravity = Gravity.LEFT;
}
nameView.setLayoutParams(layoutParams);
return convertView;
}
}
}
public static final String USER_EXTRA = "USER";
public static final String TAG = "ChatActivity";
private ArrayList<Message> mMessages;
private MessagesAdapter mAdapter;
private String mRecipient;
private ListView mListView;
private Date mLastMessageDate = new Date();
private String mConvoId;
private MessageSource.MessagesListener mListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecipient = "Rohit";
mListView = (ListView)findViewById(R.id.message_list);
mMessages = new ArrayList<>();
mAdapter = new MessagesAdapter(mMessages);
mListView.setAdapter(mAdapter);
setTitle(mRecipient);
if (getSupportActionBar() != null){
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button sendMessage = (Button)findViewById(R.id.send_message);
sendMessage.setOnClickListener(this);
String[] ids = {"Barun","-", "Rohit"};
Arrays.sort(ids);
mConvoId = ids[0]+ids[1]+ids[2];
mListener = MessageSource.addMessagesListener(mConvoId, this);
}
public void onClick(View v) {
EditText newMessageView = (EditText)findViewById(R.id.new_message);
String newMessage = newMessageView.getText().toString();
newMessageView.setText("");
Message msg = new Message();
msg.setmDate(new Date());
msg.setmText(newMessage);
msg.setmSender("Rohit");
MessageSource.saveMessage(msg, mConvoId);
}
@Override
public void onMessageAdded(Message message) {
mMessages.add(message);
mAdapter.notifyDataSetChanged();
}
@Override
protected void onDestroy() {
super.onDestroy();
MessageSource.stop(mListener);
}
private class MessagesAdapter extends ArrayAdapter<Message> {
MessagesAdapter(ArrayList<Message> messages){
super(MainActivity.this, R.layout.item, R.id.msg, messages);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = super.getView(position, convertView, parent);
Message message = getItem(position);
TextView nameView = (TextView)convertView.findViewById(R.id.msg);
nameView.setText(message.getmText());
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams)nameView.getLayoutParams();
int sdk = Build.VERSION.SDK_INT;
if (message.getmSender().equals("Rohit")){
if (sdk >= Build.VERSION_CODES.JELLY_BEAN) {
nameView.setBackground(getDrawable(R.drawable.bubble_right_green));
} else{
nameView.setBackgroundDrawable(getDrawable(R.drawable.bubble_right_green));
}
layoutParams.gravity = Gravity.RIGHT;
}else{
if (sdk >= Build.VERSION_CODES.JELLY_BEAN) {
nameView.setBackground(getDrawable(R.drawable.bubble_left_gray));
} else{
nameView.setBackgroundDrawable(getDrawable(R.drawable.bubble_left_gray));
}
layoutParams.gravity = Gravity.LEFT;
}
nameView.setLayoutParams(layoutParams);
return convertView;
}
}
}
9. Design your xml files like below.
activity_main.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:orientation ="vertical"
tools:context=".MainActivity" >
<ListView
android:id ="@+id/message_list"
android:layout_weight="100"
android:layout_width="match_parent"
android:layout_height="0dp"
android:divider="@null"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id ="@+id/new_message"
android:layout_weight="100"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<Button
android:id ="@+id/send_message"
android:text ="send"
android:background="@color/colorPrimary"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
<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:orientation ="vertical"
tools:context=".MainActivity" >
<ListView
android:id ="@+id/message_list"
android:layout_weight="100"
android:layout_width="match_parent"
android:layout_height="0dp"
android:divider="@null"
/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id ="@+id/new_message"
android:layout_weight="100"
android:layout_width="0dp"
android:layout_height="wrap_content"/>
<Button
android:id ="@+id/send_message"
android:text ="send"
android:background="@color/colorPrimary"
android:textColor="@android:color/white"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
item.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">
<TextView
android:id="@+id/msg"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/msg"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
10. Your manifest.xml is like below .
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prosen.mchat">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".ChatLife"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.prosen.mchat">
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".ChatLife"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

You may also like
Comments ( 7 )

Syeda Azka Gilani:
I am getting an error in MessageSource Java class. It is unable to to resolve message.getmDate(), message.getmText()
I am getting an error in MessageSource Java class. It is unable to to resolve message.getmDate(), message.getmText()

Admin:
If you are getting error after download the source code .. please visit my youtube video
If you are getting error after download the source code .. please visit my youtube video

Abhishek Nath:
message add to my Firebase but how reply send to user in that application
message add to my Firebase but how reply send to user in that application

Admin:
have u seen the video of Firebase Application
have u seen the video of Firebase Application

Ahmed Elsaadany:
no message found in my firebase i added true firebase url but no message in firebase database
no message found in my firebase i added true firebase url but no message in firebase database

Admin:
check the problem properly ..you have done something wrong
check the problem properly ..you have done something wrong

DK Shah:
Please Send Your Youtube Video Link..
Please Send Your Youtube Video Link..

Pravy Das:
Plz post your Youtube video link
Plz post your Youtube video link

john nero:
Is there any form is encryption used?
Is there any form is encryption used?

john nero:
Please is there any form of encryption used?
Please is there any form of encryption used?
Subscribe Latest Information
Categories
Most Popular Posts
How to Withdraw Money from ATM Machine 7steps 1178804 Views
How to Create Chat Application in Android Studio 151644 Views
How to Create a Shopping Cart Application in Android 114503 Views
You May Like Also
How to create your first Android Game 15747 Views
How to Create Chat Application in Android Studio 151644 Views
How to Create a Shopping Cart Application in Android 114503 Views
How to Make a PopUp Window in Android 55025 Views