Loading...

Xamarin.Android Chat Application using Firebase Auth and Database

View: 730    Dowload: 4   Comment: 0   Post by: admin   Category: Android   Fields: Other

Download  xamarin-android-chat.zip (55.34 KB)

You need to Sign In to download the file xamarin-android-chat.zip
If you do not have an account then Sign up for free here

In this article, I will show you how to build a Xamarin.Android chat application using Firebase Auth and Database.

Introduction

Hello everyone, I am glade that you are here to learn some amazing staff. In this episode, i shall show you how to make chat application with Firebase on Xamarin Android.  This chat application is based on Firebase Auth and Firebase Database by using Xamarin.Firebase plugins.

Background

What is Firebase?

Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014.

Firebase Auth

Firebase Auth is a service that can authenticate users using only client-side code. It supports social login providers Facebook, GitHub, Twitter and Google. Additionally, it includes a user management system whereby developers can enable user authentication with email and password login stored with Firebase.

Realtime Database

Firebase provides a realtime database and backend as a service. The service provides application developers an API that allows application data to be synchronized across clients and stored on Firebase's cloud. The company provides client libraries that enable integration with Android, iOS, JavaScript, Java, Objective-C, swift and Node.js applications. The database is also accessible through a REST API and bindings for several JavaScript frameworks such as AngularJS, React, Ember.js and Backbone.js. The REST API uses the Server-Sent Events protocol, which is an API for creating HTTP connections for receiving push notifications from a server. Developers using the realtime database can secure their data by using the company's server-side-enforced security rules.

The prerequisites

  • Before using Firebase Real-time Database, make sure that you have connected your Android app to Firebase.
  • Register Application to Firebase
  • Firebase.Xamarin Nuget Package
  • Firebase Database Nuget Package
  • Firebase Auth Nuget Package
  • Android Support Library v7 AppCompat
  • Android Support Design Library
  • Visual Studio 2017

The steps given below are required to be followed in order to create a chat app in Xamarin.Android, using Visual Studio.

Step 1 - Create a Project

Open Visual Studio and go to New Project-> Templates-> Visual C#-> Android-> Blank app. Give it a name like ChatAppUsingFirebase.

Step 2 - Install Android Support Library v7 AppCompat

Go to Solution Explorer-> Project Name-> References. Then, right-click "Manage NuGet Packages" and search for AppCompat. Install the AppCompat package.

Step 3 - Install Android Support Design Library

Again Solution Explorer-> Project Name-> References. Then, right-click "Manage NuGet Packages" and search for Design Library. Install the Design Library package.

Step 4 - Install Xamarin.Firebase.Auth Nuget Package

Similarly, install the Xamarin Firebase Auth package and Xamarin.Firebase package.

Step 5 - Install Xamarin.FIrebase.Database Nuget Package

Similarly, install the Xamarin Firebase Database package to your application.

Step 6 - Connect an Android app to FireBase

Go to firebase site by using this link "https://console.firebase.google.com/u/0/", then go to the console and click on Add Project. Enter Project name and Country and then click on "Create Project". Now, click on ‘Add Firebase to your Android App’ and copy the package name of your app followed by a click on Register App. All other fields are optional and can be left blank for now. In next step, download the google-services.json file and copy it to the app folder of your Android project. Next go to Project Source folder, find the ProjectName.csproj file. Open and edit to add the code given below for Google-services.json config.

<ItemGroup>

<GoogleServicesJson Include="google-services.json" />

</ItemGroup>

Step 7 - Email Authentication

By default Email/Password Authentication option is disable. You need to do enable it therefore go to Firebase Console, select your project, and click on "Authentication" tab. Click on Sign-in method, select Email/Password, and enable it.

Step 8 - Database access permissions

By default, the read and write access to your database is restricted. So, only authenticated users can read or write a data. If you haven’t added an authentication system to your app, it’s the right time to do it. You can also change the Firebase database rules that allow access to the data without requiring authentication. But it is not recommended as it makes your database publicly accessible to anyone.

For this, go to Firebase console and select your project. Now, click on Database and then select RULES tab. Replace the following code with Firebase Database Rules and hit "Publish" button.

Step 9 - Create SignIn Page

Next, add a new Layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right-click to add a new item, select Layout, give it a name as 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 10 - 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 11 - Create SignIn 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 putting 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 12 - 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 13 - 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 7 - 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 14 - 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;
        }
    }
}

Step 15 - Add Icon into Drawable

Open Solution Explorer -> Project Name -> Resources-> Drawable. Paste "Send"  icon into the drawable folder.

Finally, we are done with our Xamarin Firebase Chat app. Just rebuild and run the project. You will have results like below. First time each user needs to sign In through his gmail account after successful signup you 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 screenshot every user are using his email address for interacting with each other on current date time.

Xamarin.Android Chat Application using Firebase Auth and Database

In this article, I will show you how to build a Xamarin.Android chat application using Firebase Auth and Database.

Posted on 19-03-2018 

Comment:

To comment you must be logged in members.

Files with category

 
File suggestion for you
Loading...
File top downloads
Loading...
Loading...
Codetitle - library source code to share, download the file to the community
Copyright © 2018. All rights reserved. codetitle Develope by Vinagon .Ltd