<h4><strong><span style="color: #000080;">Firebase</span></strong></h4>
<p>A fully managed platform for building<strong><span style="color: #008000;"> iOS, Android, and web apps</span></strong> that provides automatic data synchronization, authentication services, messaging, file storage, analytics, and more.</p>
<p>All the data is stored in <span style="color: #008000;"><strong>JSON</strong></span> format and any changes in data, reflects immediately by performing a <strong><span style="color: #008000;">sync</span></strong> across all the <strong><span style="color: #008000;">platforms</span></strong> &; <strong><span style="color: #008000;">devices</span></strong>. This allows us to build more flexible <strong><span style="color: #008000;">realtime apps</span></strong> easily with minimal effort.</p>
<p>This article covers basics integration of firebase <strong><span style="color: #008000;">Realtime Database</span></strong> and <strong><span style="color: #008000;">Storage</span></strong>. The other concepts like performs <strong><span style="color: #008000;">data validations</span></strong>, firebase <strong><span style="color: #008000;">access rules</span></strong> also covered. If you are new to firebase, then this article helps you a lot in understanding the basic knowledge of working with firebase.</p>
<p> ;</p>
<p><img class="aligncenter wp-image-318 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/Screenshot_2018-03-23-18-17-501.png" alt="" width="480" height="800" /></p>
<h4><strong><span style="color: #000080;">1. How the Data is Stored – JSON Structured</span></strong></h4>
<p>Firebase realtime database is a <strong><span style="color: #008000;">schemaless</span></strong> database in which the data is stored in<span style="color: #008000;"><strong> JSON </strong></span>format. Basically the entire database is a big JSON tree with multiple <strong><span style="color: #008000;">nodes</span></strong>. So when you plan your database, you need to prepare the json structure in way that the data is accessible in easier way by <strong><span style="color: #008000;">avoiding nesting of child nodes</span></strong>.</p>
<p>Here is an example of storing list of message in<strong><span style="color: #008000;"> json</span></strong> tree. You can go through firebase <span style="color: #000080;"><strong><a style="color: #000080;" href="https://firebase.google.com/docs/database/android/structure-data">Structure Your Database</a></strong></span> guide to learn the best practices while defining the database structure.</p>
<p> ;</p>
<p><img class="aligncenter wp-image-308 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/json2-1.jpg" alt="" width="610" height="294" /></p>
<p> ;</p>
<h4><strong><span style="color: #000080;">2. Offline Data</span></strong></h4>
<p>Firebase provides great support when comes to offline data. It automatically stores the data offline when there is no<strong><span style="color: #008000;"> internet</span> </strong>connection. When the device connects to internet, all the data will be pushed to <span style="color: #008000;"><strong>realtime database</strong></span>. However enabling <span style="color: #008000;"><strong>disk persistence</strong></span> stores the data offline even though app restarts. Disk persistence can be <span style="color: #008000;"><strong>enabled</strong></span> by calling below one line code. Here is complete guide about firebase<strong><span style="color: #000080;"> <a style="color: #000080;" href="https://firebase.google.com/docs/database/android/offline-capabilities">offline capabilities</a></span></strong>.</p>
<pre><span style="color: #008000;"><strong>//supports offline data</strong></span>
FirebaseDatabase.getInstance().setPersistenceEnabled(true);</pre>
<h4><strong><span style="color: #000080;">3. Inserting Data</span></strong></h4>
<p>The realtime database accepts multiple data types <span style="color: #008000;"><strong>String</strong>, <strong>Long</strong>, <strong>Double</strong>, <strong>Boolean</strong>, <strong>Map<;String, Object>;</strong>, <strong>List<;Object>;</strong></span> to store the data. You can also use <span style="color: #008000;"><strong>custom java objects</strong></span> to store the data which is very helpful when storing model class directly in database.</p>
<p>Let’s say you want to store <span style="color: #008000;"><strong>message details </strong></span>in the database. First you need to create model with an <strong><span style="color: #008000;">empty constructor</span></strong> and other properties.</p>
<pre>public class FriendlyMessage {

 private String text;
 private String name;
 private String photoUrl;


<span style="color: #008000;"><strong>// Default constructor required for calls to</strong></span>
<span style="color: #008000;"><strong>// DataSnapshot.getValue(FriendlyMessage.class)</strong></span>
 public FriendlyMessage() {
 }

 public FriendlyMessage(String text, String name, String photoUrl) {
 this.text = text;
 this.name = name;
 this.photoUrl = photoUrl;
 }

}</pre>
<p>As every <span style="color: #008000;"><strong>FriendlyMessage</strong></span> needs a unique Id, you can generate one by calling <span style="color: #008000;"><em><strong>push()</strong></em></span> method which creates an empty node with unique key. Then get the reference to <span style="color: #008000;"><strong>‘message’</strong></span> node using <span style="color: #008000;"><em><strong>child()</strong></em></span> method. Finally use<span style="color: #008000;"> <em><strong>setValue()</strong></em></span> method to store the FriendlyMessage data.</p>
<p> ;</p>
<pre>DatabaseReference mMessagesDatabaseRef;
<span style="color: #008000;"><strong>//database reference</strong></span>
mMessagesDatabaseRef = FirebaseDatabase.getInstance().getReference().child("message");
<strong><span style="color: #008000;">// creating FriendlyMessage object</span></strong>
FriendlyMessage message = new FriendlyMessage(text, mUsername, null);
<strong><span style="color: #008000;">// pushing message to 'message' node using the userId</span></strong>
<strong><span style="color: #008000;">//push() will automatically generate a uniqueId</span></strong>
mMessagesDatabaseRef.push().setValue(message);

</pre>
<p>By running the above code, a new user node will be inserted in database with a unique key value.</p>
<p><img class="aligncenter wp-image-308 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/json2-1.jpg" alt="" width="610" height="294" /></p>
<h4><strong><span style="color: #000080;">4. Reading Data</span></strong></h4>
<p>To read the data, you need to attach the <span style="color: #008000;"><strong>ChildEventListener()</strong></span> to the database reference. This event will be triggered for all existing childs and also for the added one.</p>
<pre>mChildEventListener = new ChildEventListener() {
 @Override
 public void onChildAdded(DataSnapshot dataSnapshot, String s) {
 FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);

 mMessageAdapter.add(friendlyMessage);
 }

 @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(DatabaseError databaseError) {

 }
};

<span style="color: #008000;"><strong>//ChildEventListener triggered for each child in message and also for the new child added</strong></span>
mMessagesDatabaseRef.addChildEventListener(mChildEventListener);

</pre>
<h4><strong><span style="color: #000080;">5. Firebase Storage</span></strong></h4>
<p><strong><span style="color: #008000;">Cloud Storage</span></strong> is built for app developers who need to store and serve user-generated content, such as <span style="color: #008000;"><strong>photos</strong></span> or <strong><span style="color: #008000;">videos</span></strong>.</p>
<ol start="5">
<li>1 <span style="color: #0000ff;"><strong>Uploading Files to Firebase Storage</strong></span></li>
</ol>
<pre>Uri selectedImageUri = data.getData();

<strong><span style="color: #008000;">//get a reference to store file at chat_photos/<;FILENAME>;</span></strong>
StorageReference photoRef = mChatPhotosStorageRef.child(selectedImageUri.getLastPathSegment());

<strong><span style="color: #008000;">//Upload file to firebase storage</span></strong>
photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<;UploadTask.TaskSnapshot>;() {
 @Override
 public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

 Uri downloadUrl = taskSnapshot.getDownloadUrl();
 
 }
});</pre>
<p> ;</p>
<ol start="5">
<li>2 <span style="color: #0000ff;"><strong>Retrieving Uploaded Files from Firebase Storage</strong></span></li>
</ol>
<pre style="padding-left: 60px;">Uri selectedImageUri = data.getData();

<span style="color: #008000;"><strong>//get a reference to store file at chat_photos/<;FILENAME>;</strong></span>
StorageReference photoRef = mChatPhotosStorageRef.child(selectedImageUri.getLastPathSegment());

<span style="color: #008000;"><strong>//Upload file to firebase storage</strong></span>
photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<;UploadTask.TaskSnapshot>;() {
 @Override
 public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

 Uri downloadUrl = taskSnapshot.getDownloadUrl();

<strong><span style="color: #008000;">//Here i am getting the upload file uri(downloadUrl) and setting it into FirebaseDatabase object
 //(mMessagesDatabaseRef) using model class object.</span></strong> 
 FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
 mMessagesDatabaseRef.push().setValue(friendlyMessage);
 }
});

</pre>
<p>Here i am getting the <span style="color: #008000;"><strong>FriendlyMessage</strong></span> object using <strong><span style="color: #008000;">dataSnapshot.getValue(FriendlyMessage.class) </span></strong>and adding it into listView using <strong><span style="color: #008000;">mMessageAdapter</span></strong>.</p>
<p> ;</p>
<pre>mChildEventListener = new ChildEventListener() {
 @Override
 public void onChildAdded(DataSnapshot dataSnapshot, String s) {
 FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);

 mMessageAdapter.add(friendlyMessage);
 }

 @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(DatabaseError databaseError) {

 }
};

<span style="color: #008000;"><strong>//ChildEventListener triggered for each child in message and also for the new child added</strong></span>
mMessagesDatabaseRef.addChildEventListener(mChildEventListener);</pre>
<p> ;</p>
<h4><strong><span style="color: #000080;">6. Security &; Rules</span></strong></h4>
<p>Firebase rules provides a way to identify user role while performing<span style="color: #008000;"><strong> read and write</strong></span> operations. These rules will acts a security layer on the server before perform any <strong><span style="color: #008000;">CRUD</span></strong> operation. By default the rules allows user to perform read &; write operation only after authentication.</p>
<p>The below rules allow authenticated users only to read or write data.</p>
<p><img class="aligncenter wp-image-309 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/Capture1.jpg" alt="" width="774" height="154" /></p>
<p>Below rules allows everyone to read &; write data without authentication.</p>
<p> ;</p>
<p><img class="aligncenter wp-image-310 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/Capture2.jpg" alt="" width="772" height="157" /></p>
<p>You can also use these rules to validate data before inserting into database. For example below rules validates the <span style="color: #008000;"><strong>name to be less than 50 chars</strong></span> and <span style="color: #008000;"><strong>text to be less than 200 chars</strong></span>.</p>
<p><img class="wp-image-311 size-full aligncenter" src="https://c1ctech.com/wp-content/uploads/2018/03/cap3.jpg" alt="" width="753" height="310" /></p>
<p>Go through firebase <strong><span style="color: #000080;"><a style="color: #000080;" href="https://firebase.google.com/docs/database/security/">security &; rules</a></span></strong> guide to learn more about the security concepts.</p>
<p> ;</p>
<p>Now we have enough knowledge to get started with an android project. Let’s create one and see how to integrate the<strong><span style="color: #008000;"> realtime database and cloud storage</span></strong> with an <strong><span style="color: #008000;">FriendlyChatApp</span></strong>.</p>
<h4><strong><span style="color: #000080;">7. Creating Android Project</span></strong></h4>
<p style="padding-left: 30px;">1. First thing you need to do is go to <span style="color: #000080;"><strong><a style="color: #000080;" href="https://firebase.google.com/">https://firebase.google.com/</a></strong></span>and make an account to gain access to their console. After you gain access to the console you can start by creating your first project.</p>
<p style="padding-left: 30px;">2. Give the package name of your project in which you are going to integrate the <strong><span style="color: #008000;">Firebase</span></strong>. Here the <strong>google-services.json </strong>file will be downloaded when you press add app button.</p>
<p><img class="aligncenter wp-image-313 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/forthpage.jpg" alt="" width="694" height="577" /></p>
<p> ;</p>
<p style="padding-left: 30px;">3. Create a new project in Android Studio from <span style="color: #008000;"><strong>File </strong><strong>⇒ New Project</strong></span>. While filling the project details, use the same package name which you gave in firebase<span style="color: #008000;"><strong> console</strong></span>.</p>
<p style="padding-left: 30px;">4. Paste the <span style="color: #008000;"><strong>google-services.json </strong></span>file to your project’s <span style="color: #008000;"><strong>app</strong></span> This step is very important as your project won’t build without this file.</p>
<p><img class="aligncenter wp-image-314 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/fifthpage.jpg" alt="" width="692" height="636" /></p>
<p style="padding-left: 30px;">5. Now open the <span style="color: #008000;"><strong>build.</strong><strong>gradle </strong></span>located in project’s home directory and add google <strong><span style="color: #008000;">playstore</span> </strong>dependency.</p>
<p style="padding-left: 30px;">6. Open<span style="color: #008000;"> </span><strong><span style="color: #008000;">app/build.gradle</span> </strong>and add <span style="color: #008000;"><strong>firebase database</strong></span> dependency.At the very bottom of the file, add <strong><span style="color: #008000;">apply plugin:</span> <span style="color: #008000;">‘com.google.gms.google-services’</span></strong></p>
<p><img class="aligncenter wp-image-315 size-full" src="https://c1ctech.com/wp-content/uploads/2018/03/sixthpage.jpg" alt="" width="699" height="639" /></p>
<!-- WP QUADS Content Ad Plugin v. 2.0.98.1 -->
<div class="quads-location quads-ad2" id="quads-ad2" style="float:none;margin:0px;">

</div>

<p style="padding-left: 30px;">7. In order to store messages, we need a <strong><span style="color: #008000;">model</span></strong> class called <span style="color: #008000;"><strong>FriendlyMessage.java</strong></span>. Create a class named <span style="color: #008000;"><strong>FriendlyMessage.java</strong></span> and add below code.</p>
<pre>package com.example.lenovo.friendlychatapp.model;


public class FriendlyMessage {

 private String text;
 private String name;
 private String photoUrl;

 <span style="color: #008000;"><strong>// Default constructor required for calls to</strong></span>
<span style="color: #008000;"><strong> // DataSnapshot.getValue(FriendlyMessage.class)</strong></span>

 public FriendlyMessage() {
 }

 public FriendlyMessage(String text, String name, String photoUrl) {
 this.text = text;
 this.name = name;
 this.photoUrl = photoUrl;
 }

 public String getText() {
 return text;
 }

 public void setText(String text) {
 this.text = text;
 }

 public String getName() {
 return name;
 }

 public void setName(String name) {
 this.name = name;
 }

 public String getPhotoUrl() {
 return photoUrl;
 }

 public void setPhotoUrl(String photoUrl) {
 this.photoUrl = photoUrl;
 }
}</pre>
<p style="padding-left: 30px;">8. Open the <span style="color: #008000;"><strong>activity_main.xml </strong></span>and add the below code.</p>
<p><span style="color: #0000ff;"><strong>activity_main.xml</strong></span></p>
<pre><;?xml version="1.0" encoding="utf-8"?>;
<;RelativeLayout 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"

 tools:context="com.example.lenovo.friendlychatapp.MainActivity">;

 <;ListView
 android:id="@+id/messageListView"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:layout_above="@+id/linearLayout"
 android:divider="@android:color/transparent"
 android:stackFromBottom="true"
 android:transcriptMode="alwaysScroll"
 tools:listitem="@layout/item_message" />;


 <;LinearLayout
 android:id="@+id/linearLayout"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:layout_alignParentBottom="true"
 android:layout_alignParentLeft="true"
 android:layout_alignParentStart="true"
 android:orientation="horizontal">;

 <;ImageButton
 android:id="@+id/photoPickerButton"
 android:layout_width="36dp"
 android:layout_height="36dp"
 android:background="@android:drawable/ic_menu_gallery" />;

 <;EditText
 android:id="@+id/messageEditText"
 android:layout_width="0dp"
 android:layout_height="wrap_content"
 android:layout_gravity="center_vertical"
 android:layout_weight="1" />;

 <;Button
 android:id="@+id/sendButton"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_gravity="bottom"
 android:enabled="false"
 android:text="send" />;

 <;/LinearLayout>;


<;/RelativeLayout>;</pre>
<p style="padding-left: 30px;">9.Open <span style="color: #008000;"><strong>item_message.xml</strong></span> and add the below code.This layout defines one single item of listview.</p>
<p><span style="color: #0000ff;"><strong>item_message.xml</strong></span></p>
<pre><;?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="wrap_content"
 android:orientation="vertical">;

 <;ImageView
 android:id="@+id/photoImageView"
 android:layout_width="match_parent"
 android:layout_height="wrap_content"
 android:adjustViewBounds="true" />;

 <;TextView
 android:id="@+id/messageTextView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="0"
 android:textAppearance="?android:attr/textAppearanceLarge"
 tools:text="Message" />;

 <;TextView
 android:id="@+id/nameTextView"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_weight="0"
 android:textAppearance="?android:attr/textAppearanceSmall"
 tools:text="Name" />;

<;/LinearLayout>;

</pre>
<p style="padding-left: 30px;">10. Open <span style="color: #008000;"><strong>MessageAdapter.Java</strong></span> and add the below code. This adapter will show list of messages retrieve from database in listview.</p>
<p><span style="color: #0000ff;"><strong>MessageAdapter.Java</strong></span></p>
<pre style="padding-left: 30px;">package com.example.lenovo.friendlychatapp;

import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.example.lenovo.friendlychatapp.model.FriendlyMessage;
import java.util.List;

public class MessageAdapter extends ArrayAdapter<;FriendlyMessage>; {

 public MessageAdapter(Context context, int resource, List<;FriendlyMessage>; objects) {
 super(context, resource, objects);
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
 if (convertView == null) {
 convertView = ((Activity) getContext()).getLayoutInflater().inflate(R.layout.item_message, parent, false);
 }

 ImageView photoImageView = (ImageView) convertView.findViewById(R.id.photoImageView);
 TextView messageTextView = (TextView) convertView.findViewById(R.id.messageTextView);
 TextView authorTextView = (TextView) convertView.findViewById(R.id.nameTextView);

 FriendlyMessage message = getItem(position);

 boolean isPhoto = message.getPhotoUrl() != null;
 if (isPhoto) {
 messageTextView.setVisibility(View.GONE);
 photoImageView.setVisibility(View.VISIBLE);
 Glide.with(photoImageView.getContext())
 .load(message.getPhotoUrl())
 .into(photoImageView);
 } else {
 messageTextView.setVisibility(View.VISIBLE);
 photoImageView.setVisibility(View.GONE);
 messageTextView.setText(message.getText());
 }
 authorTextView.setText(message.getName());

 return convertView;
 }
}
</pre>
<p style="padding-left: 30px;">11. Open <strong><span style="color: #008000;">MainActivity.Java</span></strong><b> </b>and add the below code. The code is very simple and easily understandable.</p>
<p><span style="color: #0000ff;"><strong>MainActivity.Java</strong></span></p>
<pre>package com.example.lenovo.friendlychatapp;

import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import com.example.lenovo.friendlychatapp.model.FriendlyMessage;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

 private static final int RC_PHOTO_PICKER = 2;


 private MessageAdapter mMessageAdapter;
 private ImageButton mPhotoPickerButton;
 private EditText mMessageEditText;
 private Button mSendButton;
 List<;FriendlyMessage>; friendlyMessages;
 ListView mMessageListView;
 private String mUsername;
 DatabaseReference mMessagesDatabaseRef;
 StorageReference mChatPhotosStorageRef;
 private ChildEventListener mChildEventListener;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

 <span style="color: #008000;"><strong>// you can give any name</strong></span>
 mUsername = "Arun Kumar";

 <strong><span style="color: #008000;">//supports offline data</span></strong>
 FirebaseDatabase.getInstance().setPersistenceEnabled(true);

 <strong><span style="color: #008000;">//database reference</span></strong>
 mMessagesDatabaseRef = FirebaseDatabase.getInstance().getReference().child("message");

 <strong><span style="color: #008000;">//storage reference</span></strong>
 mChatPhotosStorageRef = FirebaseStorage.getInstance().getReference().child("chat_photos");

 <strong><span style="color: #008000;">// Initialize references to views</span></strong>
 mMessageListView = (ListView) findViewById(R.id.messageListView);
 mPhotoPickerButton = (ImageButton) findViewById(R.id.photoPickerButton);
 mMessageEditText = (EditText) findViewById(R.id.messageEditText);
 mSendButton = (Button) findViewById(R.id.sendButton);

 <strong><span style="color: #008000;">// Initialize message ListView and its adapter</span></strong>
 friendlyMessages = new ArrayList<;>;();
 mMessageAdapter = new MessageAdapter(this, R.layout.item_message, friendlyMessages);
 mMessageListView.setAdapter(mMessageAdapter);


 <strong><span style="color: #008000;">// Enable Send button when there's text to send</span></strong>
 mMessageEditText.addTextChangedListener(new TextWatcher() {
 @Override
 public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
 }

 @Override
 public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
 if (charSequence.toString().trim().length() >; 0) {
 mSendButton.setEnabled(true);
 } else {
 mSendButton.setEnabled(false);
 }
 }

 @Override
 public void afterTextChanged(Editable editable) {
 }
 });


 <strong><span style="color: #008000;">// Send button sends a message and clears the EditText</span></strong>
 mSendButton.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
 <strong><span style="color: #008000;">// Send messages on click</span></strong>
 String text = mMessageEditText.getText().toString();

 <strong><span style="color: #008000;">// creating FriendlyMessage object</span></strong>
 FriendlyMessage message = new FriendlyMessage(text, mUsername, null);

 <strong><span style="color: #008000;">// pushing message to 'message' node using the userId</span></strong>
<strong><span style="color: #008000;"> //push() will automatically generate a uniqueId</span></strong>
 mMessagesDatabaseRef.push().setValue(message);

 <strong><span style="color: #008000;">// Clear input box</span></strong>
 mMessageEditText.setText("");
 }
 });


 mChildEventListener = new ChildEventListener() {
 @Override
 public void onChildAdded(DataSnapshot dataSnapshot, String s) {
 FriendlyMessage friendlyMessage = dataSnapshot.getValue(FriendlyMessage.class);

 mMessageAdapter.add(friendlyMessage);
 }

 @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(DatabaseError databaseError) {

 }
 };

 <strong><span style="color: #008000;">//ChildEventListener triggered for each child in message and also for the new child added</span></strong>
 mMessagesDatabaseRef.addChildEventListener(mChildEventListener);

 <strong><span style="color: #008000;">// ImagePickerButton shows an image picker to upload a image for a message</span></strong>
 mPhotoPickerButton.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {

 <strong><span style="color: #008000;">// ImagePickerButton shows an image picker to upload a image for a message</span></strong>

 Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
 intent.setType("image/jpeg");
 intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
 startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);

 }
 });

 }


 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 if (requestCode == RC_PHOTO_PICKER &;&; resultCode == RESULT_OK) {

 Uri selectedImageUri = data.getData();

 <span style="color: #008000;"><strong>//get a reference to store file at chat_photos/<;FILENAME>;</strong></span>
 StorageReference photoRef = mChatPhotosStorageRef.child(selectedImageUri.getLastPathSegment());

 <strong><span style="color: #008000;">//Upload file to firebase storage</span></strong>
 photoRef.putFile(selectedImageUri).addOnSuccessListener(new OnSuccessListener<;UploadTask.TaskSnapshot>;() {
 @Override
 public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {

 Uri downloadUrl = taskSnapshot.getDownloadUrl();
 FriendlyMessage friendlyMessage = new FriendlyMessage(null, mUsername, downloadUrl.toString());
 mMessagesDatabaseRef.push().setValue(friendlyMessage);
 }
 });

 }
 }


}</pre>
<p><span style="color: #008000;"><b>When you run the app it will look like this :</b></span></p>
<p> ;</p>
<p><img class="alignnone wp-image-318" src="https://c1ctech.com/wp-content/uploads/2018/03/Screenshot_2018-03-23-18-17-501-180x300.png" alt="" width="215" height="358" /></p>
<p> ;</p>
<p><strong><span style="color: #008000;">When you click on ImagePicker button it will ask <span style="color: #003366;">Complete action Using</span>.Using one select an image you want to send and then click ok.</span></strong></p>
<p> ;</p>
<p><img class="alignnone wp-image-316" src="https://c1ctech.com/wp-content/uploads/2018/03/Screenshot_2018-03-23-18-19-221-180x300.png" alt="" width="200" height="333" /> <img class="alignnone wp-image-317" src="https://c1ctech.com/wp-content/uploads/2018/03/Screenshot_2018-03-23-18-20-491-180x300.png" alt="" width="200" height="334" /></p>
<p> ;</p>
<p> ;</p>


