Xamarin.Android - Chat Application Using Firebase - Part Two

Introduction

In this part, I will be completing the remaining process of creating a Chat Application using Firebase. Refer to part one from the following link.

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.

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.   
  6. <LinearLayout  
  7.   android:orientation="vertical"  
  8.   android:layout_centerInParent="true"  
  9.   android:layout_width="match_parent"  
  10.   android:layout_height="wrap_content">  
  11.   
  12.   <EditText  
  13.   android:id="@+id/edtEmail"  
  14.   android:inputType="textEmailAddress"  
  15.   android:hint="Enter your Email"  
  16.   android:layout_width="match_parent"  
  17.   android:layout_height="wrap_content"/>  
  18.     
  19. <EditText  
  20.   android:id="@+id/edtPassword"  
  21.   android:inputType="textPassword"  
  22.   android:hint="Enter your Password"  
  23.   android:layout_width="match_parent"  
  24.   android:layout_height="wrap_content"/>  
  25.   
  26.   <Button  
  27.     android:id="@+id/btnSingIn"  
  28.   android:text="SignIn"  
  29.   android:layout_width="match_parent"  
  30.   android:layout_height="wrap_content"/>  
  31.   
  32. </LinearLayout>  
  33. </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)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:padding="16dp"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.       
  7.     <android.support.design.widget.FloatingActionButton   
  8.       android:layout_width="wrap_content"   
  9.       android:layout_height="wrap_content"   
  10.       android:clickable="true"   
  11.       android:src="@drawable/send"   
  12.       android:id="@+id/fab"   
  13.       android:tint="@android:color/white"   
  14.       android:layout_alignParentBottom="true"   
  15.       android:layout_alignParentEnd="true"/>    
  16.     <EditText  
  17.         android:layout_toLeftOf="@+id/fab"  
  18.         android:layout_alignParentBottom="true"  
  19.         android:layout_alignParentStart="true"  
  20.         android:layout_width="match_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:hint="Your message"  
  23.         android:id="@+id/input" />  
  24.     <ListView  
  25.         android:layout_width="match_parent"  
  26.         android:layout_height="match_parent"  
  27.         android:layout_above="@+id/fab"  
  28.         android:layout_alignParentTop="true"  
  29.         android:layout_alignParentStart="true"  
  30.         android:divider="@android:color/transparent"  
  31.         android:dividerHeight="16dp"  
  32.         android:id="@+id/list_of_messages"  
  33.         android:layout_marginBottom="16dp" />  
  34. </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)

  1. using Android.App;  
  2. using Android.Gms.Tasks;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using Android.Widget;  
  6. using Firebase.Auth;  
  7.   
  8. namespace ChatAppUsingFirebase  
  9. {  
  10.     [Activity(Label = "SignIn", Theme ="@style/Theme.AppCompat.Light.NoActionBar")]  
  11.     public class SignIn : AppCompatActivity, IOnCompleteListener  
  12.     {  
  13.         FirebaseAuth auth;  
  14.   
  15.         public void OnComplete(Task task)  
  16.         {  
  17.             if (task.IsComplete)  
  18.             {  
  19.                 Toast.MakeText(this"Sign In Successful !", ToastLength.Short).Show();  
  20.                 Finish();  
  21.             }  
  22.             else  
  23.             {  
  24.                 Toast.MakeText(this"Sing In field !", ToastLength.Short).Show();  
  25.                 Finish();  
  26.             }  
  27.         }  
  28.   
  29.         protected override void OnCreate(Bundle savedInstanceState)  
  30.         {  
  31.             base.OnCreate(savedInstanceState);  
  32.             SetContentView(Resource.Layout.SignIn);  
  33.             auth = FirebaseAuth.Instance;  
  34.             // Create your application here  
  35.             var edtEmail = FindViewById<EditText>(Resource.Id.edtEmail);  
  36.             var edtPassword = FindViewById<EditText>(Resource.Id.edtPassword);  
  37.             var btnSignIn = FindViewById<Button>(Resource.Id.btnSingIn);  
  38.             btnSignIn.Click += delegate   
  39.             {  
  40.                 auth.CreateUserWithEmailAndPassword(edtEmail.Text, edtPassword.Text)  
  41.                 .AddOnCompleteListener(this);  
  42.             };  
  43.         }  
  44.     }  
  45. }  

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)

  1. using System;  
  2. namespace ChatAppUsingFirebase  
  3. {  
  4.     internal class MessageContent  
  5.     {  
  6.         public string Email { getset; }  
  7.         public string Message { getset; }  
  8.         public string Time { getset; }  
  9.         public MessageContent() { }  
  10.         public MessageContent(string Email, string Message)  
  11.         {  
  12.             this.Email = Email;  
  13.             this.Message = Message;  
  14.             Time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");  
  15.         }  
  16.     }  
  17. }  

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)

  1. using Android.App;  
  2. using Android.Content;  
  3. using Android.OS;  
  4. using Android.Runtime;  
  5. using Android.Support.Design.Widget;  
  6. using Android.Support.V7.App;  
  7. using Android.Widget;  
  8. using Firebase.Auth;  
  9. using Firebase.Database;  
  10. using Firebase.Xamarin.Database;  
  11. using System.Collections.Generic;  
  12.    
  13. namespace ChatAppUsingFirebase  
  14. {  
  15.     [Activity(Label = "ChatAppUsingFirebase", MainLauncher = true, Theme ="@style/Theme.AppCompat.Light.NoActionBar")]  
  16.     public class MainActivity : AppCompatActivity, IValueEventListener  
  17.     {  
  18.         private FirebaseClient firebaseClient;  
  19.         private List<MessageContent> lstMessage = new List<MessageContent>();  
  20.         private ListView lstChat;  
  21.         private EditText edtChat;  
  22.         private FloatingActionButton fab;  
  23.    
  24.         public int MyResultCode = 1;  
  25.    
  26.         protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)  
  27.         {  
  28.             base.OnActivityResult(requestCode, resultCode, data);  
  29.         }  
  30.           
  31.         protected override void OnCreate(Bundle savedInstanceState)  
  32.         {  
  33.             base.OnCreate(savedInstanceState);  
  34.    
  35.             // Set our view from the "main" layout resource  
  36.             SetContentView(Resource.Layout.Main);  
  37.             firebaseClient = new FirebaseClient(GetString(Resource.String.firebase_database_url));  
  38.             FirebaseDatabase.Instance.GetReference("chats").AddValueEventListener(this);  
  39.             fab = FindViewById<FloatingActionButton>(Resource.Id.fab);  
  40.             edtChat = FindViewById<EditText>(Resource.Id.input);  
  41.             lstChat = FindViewById<ListView>(Resource.Id.list_of_messages);  
  42.    
  43.             fab.Click += delegate { PostMessage(); };  
  44.    
  45.             if (FirebaseAuth.Instance.CurrentUser == null)  
  46.                 StartActivityForResult(new Android.Content.Intent(thistypeof(SignIn)), MyResultCode);  
  47.             else  
  48.             {  
  49.                 Toast.MakeText(this"Welcome" + FirebaseAuth.Instance.CurrentUser.Email, ToastLength.Short).Show();  
  50.                 DisplayChatMessage();  
  51.             }  
  52.         }  
  53.    
  54.         private async void PostMessage()  
  55.         {  
  56.             var items = await firebaseClient.Child("chats").PostAsync(new MessageContent(FirebaseAuth.Instance.CurrentUser.Email, edtChat.Text));  
  57.             edtChat.Text = "";  
  58.         }  
  59.         public void OnCancelled(DatabaseError error)  
  60.         {  
  61.    
  62.         }  
  63.    
  64.         public void OnDataChange(DataSnapshot snapshot)  
  65.         {  
  66.             DisplayChatMessage();  
  67.         }  
  68.    
  69.         private async void DisplayChatMessage()  
  70.         {  
  71.             lstMessage.Clear();  
  72.             var items = await firebaseClient.Child("chats")  
  73.                 .OnceAsync<MessageContent>();  
  74.             foreach (var item in items)  
  75.                 lstMessage.Add(item.Object);  
  76.             ListViewAdapter adapter = new ListViewAdapter(this, lstMessage);  
  77.             lstChat.Adapter = adapter;  
  78.         }    
  79.     }  

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)

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent">  
  5.     <TextView  
  6.         android:layout_width="wrap_content"  
  7.         android:layout_height="wrap_content"  
  8.         android:layout_alignParentTop="true"  
  9.         android:layout_alignParentStart="true"  
  10.         android:id="@+id/message_user"  
  11.         android:textStyle="normal|bold" />  
  12.     <TextView  
  13.         android:layout_width="wrap_content"  
  14.         android:layout_height="wrap_content"  
  15.         android:layout_alignBottom="@+id/message_user"  
  16.         android:layout_alignParentEnd="true"  
  17.         android:id="@+id/message_time" />  
  18.     <TextView  
  19.         android:layout_width="wrap_content"  
  20.         android:layout_height="wrap_content"  
  21.         android:layout_below="@+id/message_user"  
  22.         android:layout_alignParentStart="true"  
  23.         android:layout_marginTop="5dp"  
  24.         android:id="@+id/message_text"  
  25.         android:textAppearance="@style/TextAppearance.AppCompat.Body1"  
  26.         android:textSize="18sp" />  
  27. </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)

  1. using Android.Content;  
  2. using Android.Views;  
  3. using Android.Widget;  
  4. using Java.Lang;  
  5. using System.Collections.Generic;  
  6.    
  7. namespace ChatAppUsingFirebase  
  8. {  
  9.     internal class ListViewAdapter : BaseAdapter  
  10.     {  
  11.         private MainActivity mainActivity;  
  12.         private List<MessageContent> lstMessage;  
  13.    
  14.         public ListViewAdapter(MainActivity mainActivity, List<MessageContent> lstMessage)  
  15.         {  
  16.             this.mainActivity = mainActivity;  
  17.             this.lstMessage = lstMessage;  
  18.         }  
  19.    
  20.         public override int Count  
  21.         {  
  22.             get { return lstMessage.Count; }  
  23.         }  
  24.    
  25.         public override Object GetItem(int position)  
  26.         {  
  27.             return position;  
  28.         }  
  29.    
  30.         public override long GetItemId(int position)  
  31.         {  
  32.             return position;  
  33.         }  
  34.    
  35.         public override View GetView(int position, View convertView, ViewGroup parent)  
  36.         {  
  37.             LayoutInflater inflater = (LayoutInflater)mainActivity.BaseContext.GetSystemService(Context.LayoutInflaterService);  
  38.             View ItemView = inflater.Inflate(Resource.Layout.List_Item, null);  
  39.             TextView message_user, message_time, message_content;  
  40.             message_user = ItemView.FindViewById<TextView>(Resource.Id.message_user);  
  41.             message_time = ItemView.FindViewById<TextView>(Resource.Id.message_time);  
  42.             message_content = ItemView.FindViewById<TextView>(Resource.Id.message_text);  
  43.    
  44.             message_user.Text = lstMessage[position].Email;  
  45.             message_time.Text = lstMessage[position].Time;  
  46.             message_content.Text = lstMessage[position].Message;  
  47.    
  48.             return ItemView;  
  49.         }  
  50.     }  
  51. }  

Result

Finally, we are finished with our Xamarin Firebase Chat app. Just rebuild and run the project. You will have results like below. The first time, each user needs to sign in to their Gmail account and after successful sign up, they can use this chat application.
 
 
 
 
 
Points of Interest

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.


Similar Articles