Like Us on Facebook

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
 
  1.  Firebase  website
  2.  Sign Up with  Google  Account
  3.  Create  an App by giving  available name.
  4.  Navigate to  API  Docs.
  5.  From Android Option go to  Android  Quickstart .

 
Now  in  Android Studio
 
  1. Create a New Android Studio project name  MChat.
  2. select minimum  API level 16 so it will run maximum of Android device that are Active on google Play then click next.
  3. select Blank Activity and your Activity name is MainActivity click next > click finish.
  4. 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+'
 }

 
 

 
And also add the below packaging option 
 
android{
 …
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);
}
}



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

 
8. Configure your MainActivity.java like below.
 
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;
  }
  }
 }
 


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>
 


 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>
 


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>

Posted By UandBlog

UandBlog is a Global Leading source of Finance, Health, Lifestyle, Technology, Gaming and Programing and other information, it is a fastest growing blog for all , for latest post or information like us on facebook , follow on Twitter, Google+ and Pinterest.

Comments ( 7 )

Syeda Azka Gilani:
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
Abhishek Nath:
message add to my Firebase but how reply send to user in that application
Admin:
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
Admin:
check the problem properly ..you have done something wrong
DK Shah:
Please Send Your Youtube Video Link..
Pravy Das:
Plz post your Youtube video link
john nero:
Is there any form is encryption used?
john nero:
Please is there any form of encryption used?

    Leave a comment..

    Click to login.

    Subscribe Latest Information

    Most Popular Posts

    You May Like Also