Introduction
Step 1: Create a Sign In page
Add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right click to add a new item, select layout, and give it the name SignIn.axml. Open this layout file and add the following code.
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <LinearLayout
- android:orientation="vertical"
- android:layout_centerInParent="true"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <EditText
- android:id="@+id/edtEmail"
- android:inputType="textEmailAddress"
- android:hint="Enter your Email"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
- <EditText
- android:id="@+id/edtPassword"
- android:inputType="textPassword"
- android:hint="Enter your Password"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
- <Button
- android:id="@+id/btnSingIn"
- android:text="SignIn"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"/>
- </LinearLayout>
- </RelativeLayout>
Step 2: Main Layout
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open this main layout file and add the following code.
(File Name: Main.axml , Folder Name: Layout)
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:padding="16dp"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <android.support.design.widget.FloatingActionButton
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:clickable="true"
- android:src="@drawable/send"
- android:id="@+id/fab"
- android:tint="@android:color/white"
- android:layout_alignParentBottom="true"
- android:layout_alignParentEnd="true"/>
- <EditText
- android:layout_toLeftOf="@+id/fab"
- android:layout_alignParentBottom="true"
- android:layout_alignParentStart="true"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="Your message"
- android:id="@+id/input" />
- <ListView
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_above="@+id/fab"
- android:layout_alignParentTop="true"
- android:layout_alignParentStart="true"
- android:divider="@android:color/transparent"
- android:dividerHeight="16dp"
- android:id="@+id/list_of_messages"
- android:layout_marginBottom="16dp" />
- </RelativeLayout>
Step 3: Create Sign In Activity
Add a new Activity. For this, open Solution Explorer-> Project Name-> right click to add a new item and select Activity. Give it a name like SignIn and add the following code, using the appropriate namespaces.
(FileName: SignIn)
- using Android.App;
- using Android.Gms.Tasks;
- using Android.OS;
- using Android.Support.V7.App;
- using Android.Widget;
- using Firebase.Auth;
- namespace ChatAppUsingFirebase
- {
- [Activity(Label = "SignIn", Theme ="@style/Theme.AppCompat.Light.NoActionBar")]
- public class SignIn : AppCompatActivity, IOnCompleteListener
- {
- FirebaseAuth auth;
- public void OnComplete(Task task)
- {
- if (task.IsComplete)
- {
- Toast.MakeText(this, "Sign In Successful !", ToastLength.Short).Show();
- Finish();
- }
- else
- {
- Toast.MakeText(this, "Sing In field !", ToastLength.Short).Show();
- Finish();
- }
- }
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- SetContentView(Resource.Layout.SignIn);
- auth = FirebaseAuth.Instance;
- // Create your application here
- var edtEmail = FindViewById<EditText>(Resource.Id.edtEmail);
- var edtPassword = FindViewById<EditText>(Resource.Id.edtPassword);
- var btnSignIn = FindViewById<Button>(Resource.Id.btnSingIn);
- btnSignIn.Click += delegate
- {
- auth.CreateUserWithEmailAndPassword(edtEmail.Text, edtPassword.Text)
- .AddOnCompleteListener(this);
- };
- }
- }
- }
Step 4: Writing MessageContent Class
Before you go further, you need to write your MessageContent class with all the getter and setter methods. For this, go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like MessageContent.cs and write the following code.
(File Name: MessageContent.cs)
- using System;
- namespace ChatAppUsingFirebase
- {
- internal class MessageContent
- {
- public string Email { get; set; }
- public string Message { get; set; }
- public string Time { get; set; }
- public MessageContent() { }
- public MessageContent(string Email, string Message)
- {
- this.Email = Email;
- this.Message = Message;
- Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
- }
- }
- }
Step 5 : Main Activity Class
Now, go to Solution Explorer-> Project Name-> MainActivity and add the following code to main activity with appropriate namespaces.
(FileName: MainActivity)
- using Android.App;
- using Android.Content;
- using Android.OS;
- using Android.Runtime;
- using Android.Support.Design.Widget;
- using Android.Support.V7.App;
- using Android.Widget;
- using Firebase.Auth;
- using Firebase.Database;
- using Firebase.Xamarin.Database;
- using System.Collections.Generic;
- namespace ChatAppUsingFirebase
- {
- [Activity(Label = "ChatAppUsingFirebase", MainLauncher = true, Theme ="@style/Theme.AppCompat.Light.NoActionBar")]
- public class MainActivity : AppCompatActivity, IValueEventListener
- {
- private FirebaseClient firebaseClient;
- private List<MessageContent> lstMessage = new List<MessageContent>();
- private ListView lstChat;
- private EditText edtChat;
- private FloatingActionButton fab;
- public int MyResultCode = 1;
- protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
- {
- base.OnActivityResult(requestCode, resultCode, data);
- }
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
- // Set our view from the "main" layout resource
- SetContentView(Resource.Layout.Main);
- firebaseClient = new FirebaseClient(GetString(Resource.String.firebase_database_url));
- FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);
- fab = FindViewById<FloatingActionButton>(Resource.Id.fab);
- edtChat = FindViewById<EditText>(Resource.Id.input);
- lstChat = FindViewById<ListView>(Resource.Id.list_of_messages);
- fab.Click += delegate { PostMessage(); };
- if (FirebaseAuth.Instance.CurrentUser == null)
- StartActivityForResult(new Android.Content.Intent(this, typeof(SignIn)), MyResultCode);
- else
- {
- Toast.MakeText(this, "Welcome" + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();
- DisplayChatMessage();
- }
- }
- private async void PostMessage()
- {
- var items = await firebaseClient.Child("chats").PostAsync(new MessageContent(FirebaseAuth.Instance.CurrentUser.Email, edtChat.Text));
- edtChat.Text = "";
- }
- public void OnCancelled(DatabaseError error)
- {
- }
- public void OnDataChange(DataSnapshot snapshot)
- {
- DisplayChatMessage();
- }
- private async void DisplayChatMessage()
- {
- lstMessage.Clear();
- var items = await firebaseClient.Child("chats")
- .OnceAsync<MessageContent>();
- foreach (var item in items)
- lstMessage.Add(item.Object);
- ListViewAdapter adapter = new ListViewAdapter(this, lstMessage);
- lstChat.Adapter = adapter;
- }
- }
Step 6 - Add Layout For List_Item
Again, add a new layout named List_Item.axml and add the following code.
(FileName: List_Item.axml)
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignParentTop="true"
- android:layout_alignParentStart="true"
- android:id="@+id/message_user"
- android:textStyle="normal|bold" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_alignBottom="@+id/message_user"
- android:layout_alignParentEnd="true"
- android:id="@+id/message_time" />
- <TextView
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_below="@+id/message_user"
- android:layout_alignParentStart="true"
- android:layout_marginTop="5dp"
- android:id="@+id/message_text"
- android:textAppearance="@style/TextAppearance.AppCompat.Body1"
- android:textSize="18sp" />
- </RelativeLayout>
Step 7 - Writing List View Adapter Class
We need to write our own class to make a custom adapter inherited from the base adapter. Go to Solution Explorer-> Project name and right-click. Select Add -> New Item-> Class. Give it a name as ListViewAdapter.cs and write the following code.
(File Name: ListViewAdapter.cs)
- using Android.Content;
- using Android.Views;
- using Android.Widget;
- using Java.Lang;
- using System.Collections.Generic;
- namespace ChatAppUsingFirebase
- {
- internal class ListViewAdapter : BaseAdapter
- {
- private MainActivity mainActivity;
- private List<MessageContent> lstMessage;
- public ListViewAdapter(MainActivity mainActivity, List<MessageContent> lstMessage)
- {
- this.mainActivity = mainActivity;
- this.lstMessage = lstMessage;
- }
- public override int Count
- {
- get { return lstMessage.Count; }
- }
- public override Object GetItem(int position)
- {
- return position;
- }
- public override long GetItemId(int position)
- {
- return position;
- }
- public override View GetView(int position, View convertView, ViewGroup parent)
- {
- LayoutInflater inflater = (LayoutInflater)mainActivity.BaseContext.GetSystemService(Context.LayoutInflaterService);
- View ItemView = inflater.Inflate(Resource.Layout.List_Item, null);
- TextView message_user, message_time, message_content;
- message_user = ItemView.FindViewById<TextView>(Resource.Id.message_user);
- message_time = ItemView.FindViewById<TextView>(Resource.Id.message_time);
- message_content = ItemView.FindViewById<TextView>(Resource.Id.message_text);
- message_user.Text = lstMessage[position].Email;
- message_time.Text = lstMessage[position].Time;
- message_content.Text = lstMessage[position].Message;
- return ItemView;
- }
- }
- }
Result
In this article, I demonstrated how you can create a chat application using Firebase Auth and Database. You can see in the screenshot that every user is using his/her email address for interacting with each other on the current date-time.