Xamarin.Android - Working With Firebase Database - Part Two

Today, we are going to learn how to save and retrieve data from Firebase in Android.

Introduction
 
In this part, I will be completing the remaining process of Firebase Database.
 
Refer to part one.
Step 1
 
Add a new XML file. For that, go to Solution Explorer-> Project Name-> Resources-> Values-> Right-click to add a new item, select XML, and give it a name such as styles.xml. Open this XML file and add the following code.
 
(Folder Name: values, File Name: styles.xml)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <resources>  
  3.   <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  
  4.     <item name="colorPrimary">@color/colorPrimary</item>  
  5.     <item name="colorPrimaryDark">@color/colorPrimaryDark</item>  
  6.     <item name="colorAccent">@color/colorAccent</item>  
  7.   </style>  
  8.   <style name="CircularProgress" parent="Theme.AppCompat.Light">  
  9.     <item name="colorAccent">@color/circularColor</item>  
  10.   </style>  
  11. </resources>  
Step 2
 
Similarly, add a new XML file - colors.xml and add the following code.
 
(Folder Name: values, File Name: colors.xml)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8" ?>   
  2. <resources>  
  3.    <color name="colorPrimary">#009688</color>    
  4.    <color name="colorPrimaryDark">#00695C</color>  
  5.    <color name="colorAccent">#64FFDA</color>  
  6.    <color name="circularColor">#9F489B</color>  
  7. </resources>  
Step 3 - Create Menu
 
Open Solution Explorer-> Project Name-> Resources-> Right-click to add a new folder with the name Menu. Right-click to Menu folder to add a new XML file name as, menu_main. Open this main XML file and add the following code.
 
(File Name: menu_main , Folder Name: Menu)
  1. <?xml version="1.0" encoding="utf-8" ?>  
  2. <menu xmlns:android="http://schemas.android.com/apk/res/android"  
  3.       xmlns:app="http://schemas.android.com/apk/res-auto">  
  4.   <item android:id="@+id/menu_add"  
  5.         android:title="Add"  
  6.         android:icon="@drawable/Add_icon"  
  7.         app:showAsAction="always"/>  
  8.   <item android:id="@+id/menu_save"  
  9.         android:title="Save"  
  10.         android:icon="@drawable/Save_icon"  
  11.         app:showAsAction="always"/>  
  12.   <item android:id="@+id/menu_delete"  
  13.         android:title="Delete"  
  14.         android:icon="@drawable/Delete_icon"  
  15.         app:showAsAction="always"/>  
  16. </menu>  
Step 4 - Writing Account Class
 
Before you go further, you need to write your Account 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 Account.cs and write the following code.
 
(File Name: Account.cs)
 
C# Code
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using Android.App;  
  6. using Android.Content;  
  7. using Android.OS;  
  8. using Android.Runtime;  
  9. using Android.Views;  
  10. using Android.Widget;  
  11. namespace FirebaseDatabase.Model  
  12. {  
  13.     public class Account  
  14.     {  
  15.         public string uid { get; set; }  
  16.         public string name { get; set; }  
  17.         public string email { get; set; }  
  18.     }  
  19. }  
Step 5 - Add Layout For List Item
 
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 list_Item.axml. Open this layout file and add the following code.
 
(Folder Name: Layout , File Name: list_Item.axml)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:orientation="vertical"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.     <TextView  
  7.         android:id="@+id/list_name"  
  8.         android:text="User"  
  9.         android:textSize="30sp"  
  10.         android:textStyle="bold"  
  11.         android:layout_width="wrap_content"  
  12.         android:layout_height="wrap_content" />  
  13.     <TextView  
  14.         android:id="@+id/list_email"  
  15.         android:text="Email"  
  16.         android:textSize="20sp"  
  17.         android:textStyle="italic"  
  18.         android:layout_width="wrap_content"  
  19.         android:layout_height="wrap_content" />  
  20. </LinearLayout>  
Step 5 - 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)
 
C# Code
  1. using Android.App;  
  2. using Android.Content;  
  3. using Android.Views;  
  4. using Android.Widget;  
  5. using FirebaseDatabase.Model;  
  6. using System.Collections.Generic;  
  7. namespace FirebaseDatabase  
  8. {  
  9.     public class ListViewAdapter : BaseAdapter  
  10.     {  
  11.         Activity activity;  
  12.         List<Account> lstAccounts;  
  13.         LayoutInflater inflater;  
  14.         public ListViewAdapter(Activity activity, List<Account> lstAccounts)  
  15.         {  
  16.             this.activity = activity;  
  17.             this.lstAccounts = lstAccounts;  
  18.         }  
  19.         public override int Count  
  20.         {  
  21.             get { return lstAccounts.Count; }  
  22.         }  
  23.         public override Java.Lang.Object GetItem(int position)  
  24.         {  
  25.             return position;  
  26.         }  
  27.         public override long GetItemId(int position)  
  28.         {  
  29.             return position;  
  30.         }  
  31.         public override View GetView(int position, View convertView, ViewGroup parent)  
  32.         {  
  33.             inflater = (LayoutInflater)activity.BaseContext.GetSystemService(Context.LayoutInflaterService);  
  34.             View itemView = inflater.Inflate(Resource.Layout.list_Item, null);  
  35.             var txtuser = itemView.FindViewById<TextView>(Resource.Id.list_name);  
  36.             var txtemail = itemView.FindViewById<TextView>(Resource.Id.list_email);  
  37.             if(lstAccounts.Count > 0)  
  38.             {  
  39.                 txtuser.Text = lstAccounts[position].name;  
  40.                 txtemail.Text = lstAccounts[position].email;  
  41.             }  
  42.             return itemView;  
  43.         }  
  44.     }  
  45. }  
Step 6 - 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 Code 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.                 xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.   <android.support.v7.widget.Toolbar  
  7.     android:id="@+id/toolbar"  
  8.     android:minHeight="?attr/actionBarSize"  
  9.     android:layout_width="match_parent"  
  10.     android:layout_height="wrap_content"  
  11.     android:background="?attr/colorPrimary"  
  12.     app:titleTextColor="@android:color/white"/>  
  13.   <android.support.design.widget.TextInputLayout  
  14.     android:layout_below="@+id/toolbar"  
  15.     android:id="@+id/txtName"  
  16.     android:layout_width="match_parent"  
  17.     android:layout_height="wrap_content">  
  18.     <EditText  
  19.       android:id="@+id/name"  
  20.       android:hint="Enter Your Name"  
  21.       android:inputType="textCapWords"  
  22.       android:maxLines="1"  
  23.       android:layout_width="match_parent"  
  24.       android:layout_height="wrap_content"/>  
  25.   </android.support.design.widget.TextInputLayout>  
  26.   <android.support.design.widget.TextInputLayout  
  27.     android:layout_below="@+id/txtName"  
  28.     android:id="@+id/txtEmail"  
  29.     android:layout_width="match_parent"  
  30.     android:layout_height="wrap_content">  
  31.     <EditText  
  32.       android:id="@+id/email"  
  33.       android:hint="Enter Your Email"  
  34.       android:inputType="textCapWords"  
  35.       android:maxLines="1"  
  36.       android:layout_width="match_parent"  
  37.       android:layout_height="wrap_content"/>  
  38.   </android.support.design.widget.TextInputLayout>  
  39.   <ListView  
  40.     android:id="@+id/list_data"  
  41.     android:layout_below="@+id/txtEmail"  
  42.     android:layout_width="match_parent"  
  43.     android:layout_height="wrap_content"/>  
  44.   <ProgressBar  
  45.     android:id="@+id/circularProgress"  
  46.     android:visibility="invisible"  
  47.     android:layout_centerInParent="true"  
  48.     android:theme="@style/CircularProgress"  
  49.     android:layout_width="match_parent"  
  50.     android:layout_height="wrap_content"  
  51.     style="@style/Widget.AppCompat.ProgressBar"/>  
  52. </RelativeLayout>  
 
Step 7 - Main Activity Class
 
Note - Must change your Firebase Database URL in Main activity class before building the project.
 
Now, go to Solution Explorer-> Project Name-> MainActivity and add the following code to main activity with appropriate namespaces.
 
(FileName: MainActivity)
 
C# Code
  1. using Android.App;  
  2. using Android.Widget;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using Android.Views;  
  6. using System.Collections.Generic;  
  7. using FirebaseDatabase.Model;  
  8. using System;  
  9. using System.Threading.Tasks;  
  10. using Firebase.Xamarin.Database;  
  11. using Firebase.Xamarin.Database.Query;  
  12. namespace FirebaseDatabase  
  13. {  
  14.     [Activity(Label = "FirebaseDatabase", MainLauncher = true , Theme ="@style/AppTheme")]  
  15.     public class MainActivity : AppCompatActivity  
  16.     {  
  17.         private EditText input_name, input_email;  
  18.         private ListView list_data;  
  19.         private ProgressBar circular_progress;  
  20.         private List<Account> list_users = new List<Account>();  
  21.         private ListViewAdapter adapter;  
  22.         private Account selectedAccount;  
  23.         private const string FirebaseURL = "https://fir-database-33529.firebaseio.com/"; //Firebase Database URL  
  24.         protected override async void OnCreate(Bundle savedInstanceState)  
  25.         {  
  26.             base.OnCreate(savedInstanceState);  
  27.             // Set our view from the "main" layout resource  
  28.             SetContentView(Resource.Layout.Main);  
  29.             //Add Toolbar  
  30.             Android.Support.V7.Widget.Toolbar toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);  
  31.             toolbar.Title = "Firebase Database";  
  32.             SetSupportActionBar(toolbar);  
  33.             //View   
  34.             circular_progress = FindViewById<ProgressBar>(Resource.Id.circularProgress);  
  35.             input_name = FindViewById<EditText>(Resource.Id.name);  
  36.             input_email = FindViewById<EditText>(Resource.Id.email);  
  37.             list_data = FindViewById<ListView>(Resource.Id.list_data);  
  38.             list_data.ItemClick += (s, e) =>  
  39.             {  
  40.                 Account account = list_users[e.Position];  
  41.                 selectedAccount = account;  
  42.                 input_name.Text = account.name;  
  43.                 input_email.Text = account.email;  
  44.             };  
  45.             await LoadData();  
  46.         }  
  47.         private async Task LoadData()  
  48.         {  
  49.             circular_progress.Visibility = ViewStates.Visible;  
  50.             list_data.Visibility = ViewStates.Invisible;  
  51.             var firebase =new FirebaseClient(FirebaseURL);  
  52.             var items = await firebase  
  53.                 .Child("users")  
  54.                 .OnceAsync<Account>();  
  55.             list_users.Clear();  
  56.             adapter = null;  
  57.             foreach (var item in items)  
  58.             {  
  59.                 Account account = new Account();  
  60.                 account.uid = item.Key;  
  61.                 account.name = item.Object.name;  
  62.                 account.email = item.Object.email;  
  63.                 list_users.Add(account);  
  64.             }  
  65.             adapter = new ListViewAdapter(this, list_users);  
  66.             adapter.NotifyDataSetChanged();  
  67.             list_data.Adapter = adapter;  
  68.             circular_progress.Visibility = ViewStates.Invisible;  
  69.             list_data.Visibility = ViewStates.Visible;  
  70.         }  
  71.         public override bool OnCreateOptionsMenu(IMenu menu)  
  72.         {  
  73.             MenuInflater.Inflate(Resource.Menu.menu_main, menu);  
  74.             return base.OnCreateOptionsMenu(menu);  
  75.         }  
  76.         public override bool OnOptionsItemSelected(IMenuItem item)  
  77.         {  
  78.             int id = item.ItemId;  
  79.             if(id == Resource.Id.menu_add)  
  80.             {  
  81.                 CreateUser();  
  82.             }  
  83.             else  
  84.             if(id == Resource.Id.menu_save) //Update  
  85.             {  
  86.                 UpdateUser(selectedAccount.uid, input_name.Text, input_email.Text);  
  87.             }  
  88.             else  
  89.             if (id == Resource.Id.menu_delete) //Delete  
  90.             {  
  91.                 DeleteUser(selectedAccount.uid);  
  92.             }  
  93.             return base.OnOptionsItemSelected(item);  
  94.         }  
  95.         private async void DeleteUser(string uid)  
  96.         {  
  97.             var firebase = new FirebaseClient(FirebaseURL);  
  98.             await firebase.Child("users").Child(uid).DeleteAsync();  
  99.             await LoadData();  
  100.         }  
  101.         private async void UpdateUser(string uid, string name, string email)  
  102.         {  
  103.             var firebase = new FirebaseClient(FirebaseURL);  
  104.             await firebase.Child("users").Child(uid).Child("name").PutAsync(name);  
  105.             await firebase.Child("users").Child(uid).Child("email").PutAsync(email);  
  106.             await LoadData();  
  107.         }  
  108.         private async void CreateUser()  
  109.         {  
  110.             Account user = new Account();  
  111.             user.uid = String.Empty;  
  112.             user.name = input_name.Text;  
  113.             user.email = input_email.Text;  
  114.             var firebase = new FirebaseClient(FirebaseURL);  
  115.             //Add Item  
  116.             var item = await firebase.Child("users").PostAsync<Account>(user);  
  117.             await LoadData();  
  118.         }  
  119.     }  
  120. }  
Step 8 - Add Icons into Drawable
 
Open Solution Explorer -> Project Name -> Resources-> Drawable. Paste "Add, Save, Delete"  icons into the drawable folder.
 
  
Output
 
 
  
Please share your comments and feedback.