Xamarin.Android - Working With Node.js And MongoDB - Part Two

Introduction

 
In part one, we had developed the RESTFul API in Node JS and Mongodb. In this article we will consume this RESTFul API in Xamarin.Android.

Client Application

 
Step 1 - Create a Xamarin Android Project
 
Open Visual Studio-> New Project-> Templates-> Visual C#-> Android-> Blank app and give the project name XamarinAuth.
 
(ProjectName: XamarinAuth)
 
 
Step 2 - Add NuGet Package
 
After creating a blank project, first, add Refit NuGet package to this project by right-clicking on References and select manage NuGet packages.
 
Step 3 - Create Login Layout
 
Next, open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open activity_main.axml file and add the following code.
 
(FileName: activity_main.axml)
  1. <?xml version="1.0" encoding="utf-8"?>    
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"    
  4.     xmlns:tools="http://schemas.android.com/tools"    
  5.     android:layout_width="match_parent"    
  6.     android:orientation="vertical"    
  7.     android:background="@android:color/white"    
  8.     android:padding="16dp"    
  9.     android:layout_margin="16dp"    
  10.     android:layout_height="match_parent">    
  11.     
  12.     <TextView    
  13.         android:layout_width="match_parent"    
  14.         android:layout_height="wrap_content"    
  15.     android:textStyle="bold"    
  16.     android:text="Login Page"    
  17.     android:textSize="25sp"    
  18.     android:textAlignment="center"    
  19.     android:textColor="@color/colorPrimary"/>    
  20.     <EditText    
  21.         android:layout_width="match_parent"    
  22.         android:layout_height="wrap_content"    
  23.         android:hint="Email"    
  24.         android:inputType="textEmailAddress"    
  25.         android:id="@+id/edt_email"/>    
  26.         <EditText    
  27.         android:layout_width="match_parent"    
  28.         android:layout_height="wrap_content"    
  29.         android:hint="Password"    
  30.         android:inputType="textPassword"    
  31.         android:id="@+id/edt_password"/>    
  32.     <LinearLayout    
  33.         android:orientation="horizontal"    
  34.         android:layout_width="match_parent"    
  35.         android:layout_height="wrap_content"    
  36.         android:weightSum="2">    
  37.         
  38.         <Button    
  39.         android:layout_width="0dp"    
  40.         android:layout_height="wrap_content"    
  41.         android:layout_weight="1"    
  42.         android:hint="Login"    
  43.         android:id="@+id/btn_login"    
  44.         android:layout_marginTop="15dp"/>    
  45.     
  46.         <Button    
  47.         android:layout_width="0dp"    
  48.         android:layout_height="wrap_content"    
  49.         android:layout_weight="1"    
  50.         android:hint="Register"    
  51.         android:id="@+id/btn_registeration"    
  52.         android:layout_marginTop="15dp"/>    
  53.     </LinearLayout>    
  54.     
  55. </LinearLayout>    
Step 3 - Create Registration Layout
 
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 activity_register.
 
Open this layout file and add the following code.
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:app="http://schemas.android.com/apk/res-auto"  
  4.     xmlns:tools="http://schemas.android.com/tools"  
  5.     android:layout_width="match_parent"  
  6.     android:orientation="vertical"  
  7.     android:background="@android:color/white"  
  8.     android:padding="16dp"  
  9.     android:layout_margin="16dp"  
  10.     android:layout_height="match_parent">  
  11.   
  12.     <TextView  
  13.     android:layout_width="match_parent"  
  14.     android:layout_height="wrap_content"  
  15.     android:textStyle="bold"  
  16.     android:text="Register Page"  
  17.     android:textSize="25sp"  
  18.     android:textAlignment="center"  
  19.     android:textColor="@color/colorPrimary"/>  
  20.     <EditText  
  21.         android:layout_width="match_parent"  
  22.         android:layout_height="wrap_content"  
  23.         android:hint="First Name"  
  24.         android:inputType="text"  
  25.         android:id="@+id/edt_fname"/>      
  26.         <EditText  
  27.         android:layout_width="match_parent"  
  28.         android:layout_height="wrap_content"  
  29.         android:hint="Last Name"  
  30.         android:inputType="text"  
  31.         android:id="@+id/edt_lname"/>          
  32.         <EditText  
  33.         android:layout_width="match_parent"  
  34.         android:layout_height="wrap_content"  
  35.         android:hint="Mobile"  
  36.         android:inputType="text"  
  37.         android:id="@+id/edt_mobile"/>          
  38.         <EditText  
  39.         android:layout_width="match_parent"  
  40.         android:layout_height="wrap_content"  
  41.         android:hint="Email"  
  42.         android:inputType="textEmailAddress"  
  43.         android:id="@+id/edt_email"/>  
  44.         <EditText  
  45.         android:layout_width="match_parent"  
  46.         android:layout_height="wrap_content"  
  47.         android:hint="Password"  
  48.         android:inputType="textPassword"  
  49.         android:id="@+id/edt_password"/>  
  50.     <LinearLayout  
  51.         android:orientation="horizontal"  
  52.         android:layout_width="match_parent"  
  53.         android:layout_height="wrap_content"  
  54.         android:weightSum="2">  
  55.   
  56.         <Button  
  57.         android:layout_width="0dp"  
  58.         android:layout_height="wrap_content"  
  59.         android:layout_weight="1"  
  60.         android:hint="Register"  
  61.         android:id="@+id/btn_register"  
  62.         android:layout_marginTop="15dp"/>  
  63.   
  64.         <Button  
  65.         android:layout_width="0dp"  
  66.         android:layout_height="wrap_content"  
  67.         android:layout_weight="1"  
  68.         android:hint="Cancel"  
  69.         android:id="@+id/btn_cancel"  
  70.         android:layout_marginTop="15dp"/>  
  71.     </LinearLayout>  
  72.           
  73. </LinearLayout>  
Step 4 - Create Dashboard Layout
 
Similarly 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 activity_dashboard. Open this layout file and add the following 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.     
  7.     <TextView    
  8.         android:layout_marginTop="20dp"    
  9.         android:layout_width="match_parent"    
  10.         android:layout_height="wrap_content"    
  11.     android:textStyle="bold"    
  12.     android:text="Welcome To Dashboard"    
  13.     android:textSize="25sp"    
  14.     android:textAlignment="center"    
  15.     android:textColor="@color/colorPrimary"/>    
  16.     
  17.         <Button    
  18.         android:layout_marginLeft="120dp"    
  19.         android:layout_width="wrap_content"    
  20.         android:layout_height="wrap_content"    
  21.         android:hint="Back To Home"    
  22.         android:id="@+id/btn_cancel"    
  23.         android:layout_marginTop="30dp"/>    
  24. </LinearLayout>    
Step 5 - Create User Model Class
 
Add a new class to your project with the name User.cs. Add the following properties to getter and setter with an appropriate namespace.
  1. public class User  
  2.     {  
  3.         public string FirstName { getset; }  
  4.         public string LastName { getset; }  
  5.         public string Email { getset; }  
  6.         public string Password { getset; }  
  7.         public string Mobile { getset; }  
  8.     }  
Step 6 - Create Register 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 RegisterActivity and add the following code, using the appropriate namespaces.
 
(FileName: RegisterActivity)
  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. using XamarinAuth.API;    
  12. using XamarinAuth.Model;    
  13. using Refit;    
  14.     
  15. namespace XamarinAuth.Activities    
  16. {    
  17.     [Activity(Label = "RegisterActivity")]    
  18.     public class RegisterActivity : Activity    
  19.     {    
  20.         IAPI _aPI;    
  21.         Button btn_register, btn_cancel;    
  22.         EditText edt_Email, edt_Password, edt_fname, edt_lname, edt_mobile;    
  23.         protected override void OnCreate(Bundle savedInstanceState)    
  24.         {    
  25.             base.OnCreate(savedInstanceState);    
  26.             SetContentView(Resource.Layout.activity_register);    
  27.             // Create your application here    
  28.             _aPI = RestService.For<IAPI>("http://10.0.2.2:3000");    
  29.     
  30.             var connection = new RestAPI(this, _aPI);    
  31.     
  32.             btn_register = FindViewById<Button>(Resource.Id.btn_register);    
  33.             btn_cancel= FindViewById<Button>(Resource.Id.btn_cancel);    
  34.             edt_lname = FindViewById<EditText>(Resource.Id.edt_lname);    
  35.             edt_mobile = FindViewById<EditText>(Resource.Id.edt_mobile);    
  36.             edt_fname = FindViewById<EditText>(Resource.Id.edt_fname);    
  37.             edt_Email = FindViewById<EditText>(Resource.Id.edt_email);    
  38.             edt_Password = FindViewById<EditText>(Resource.Id.edt_password);    
  39.     
  40.             btn_cancel.Click += delegate { StartActivity(typeof(MainActivity)); };    
  41.             btn_register.Click += async delegate    
  42.             {    
  43.                 var user = new User    
  44.                 {    
  45.                     FirstName = edt_fname.Text.ToString(),    
  46.                     LastName = edt_lname.Text.ToString(),    
  47.                     Mobile = edt_mobile.Text.ToString(),    
  48.                     Email = edt_Email.Text.ToString(),    
  49.                     Password = edt_Password.Text.ToString(),    
  50.                 };    
  51.                 var result = await connection.RegisterUserAsync(user);    
  52.                 if(result == true)    
  53.                 {    
  54.                     StartActivity(typeof(MainActivity));    
  55.                 }    
  56.             };    
  57.         }    
  58.     }    
  59. }    
Step 7 - Create Dashboard 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 DashboardActivity and add the following code, using the appropriate namespaces.
 
(FileName: DashboardActivity)
  1. using Android.App;    
  2. using Android.OS;    
  3. using Android.Widget;    
  4.     
  5. namespace XamarinAuth.Activities    
  6. {    
  7.     [Activity(Label = "DashboardActivity")]    
  8.     public class DashboardActivity : Activity    
  9.     {    
  10.         Button btn_backToHome;    
  11.         protected override void OnCreate(Bundle savedInstanceState)    
  12.         {    
  13.             base.OnCreate(savedInstanceState);    
  14.             SetContentView(Resource.Layout.activity_dashboard);    
  15.             // Create your application here    
  16.             btn_backToHome = FindViewById<Button>(Resource.Id.btn_cancel);    
  17.     
  18.             btn_backToHome.Click += delegate    
  19.             {    
  20.                 StartActivity(typeof(MainActivity));    
  21.             };    
  22.         }    
  23.     }    
  24. }     
Step 8 - Add API Interface
 
Before you go further, you need to write your IAPI 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 IAPI.cs and write the following code.
 
(File Name: IAPI.cs)
  1. using Refit;  
  2. using System.Collections.Generic;  
  3. using System.Threading.Tasks;  
  4.   
  5. namespace XamarinAuth.API  
  6. {  
  7.     public interface IAPI  
  8.     {  
  9.         [Post("/login")]  
  10.         Task<string> SignIn([Body(BodySerializationMethod.UrlEncoded)] Dictionary<stringobject> data);  
  11.         [Post("/register")]  
  12.         Task<string> SignUp([Body(BodySerializationMethod.UrlEncoded)] Dictionary<stringobject> data);  
  13.     }  
  14. }  
Step 9 - Add RestAPI Class
 
Before you go further, you need to write your RestAPI 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 RestAPI.cs and write the following code.
 
(File Name: RestAPI.cs)
  1. using Android.Content;  
  2. using Android.Widget;  
  3. using XamarinAuth.Model;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Threading.Tasks;  
  7.   
  8. namespace XamarinAuth.API  
  9. {  
  10.     public class RestAPI  
  11.     {  
  12.         IAPI _aPI;  
  13.         Context _context;  
  14.         public RestAPI(Context context, IAPI aPI)  
  15.         {  
  16.             _aPI = aPI;  
  17.             _context = context;  
  18.         }  
  19.         public async Task<bool> RegisterUserAsync(User user)  
  20.         {  
  21.             if (String.IsNullOrEmpty(user.FirstName))  
  22.             {  
  23.                 Toast.MakeText(_context, "FirstName can not be null or empty!", ToastLength.Short).Show();  
  24.                 return false;  
  25.             }  
  26.             if (String.IsNullOrEmpty(user.LastName))  
  27.             {  
  28.                 Toast.MakeText(_context, "LastName can not be null or empty!", ToastLength.Short).Show();  
  29.                 return false;  
  30.             }  
  31.             if (String.IsNullOrEmpty(user.Email))  
  32.             {  
  33.                 Toast.MakeText(_context, "Email can not be null or empty!", ToastLength.Short).Show();  
  34.                 return false;  
  35.             }  
  36.             if (String.IsNullOrEmpty(user.Mobile))  
  37.             {  
  38.                 Toast.MakeText(_context, "Mobile Number can not be null or empty!", ToastLength.Short).Show();  
  39.                 return false;  
  40.             }  
  41.             if (String.IsNullOrEmpty(user.Password))  
  42.             {  
  43.                 Toast.MakeText(_context, "Password can not be null or empty!", ToastLength.Short).Show();  
  44.                 return false;  
  45.             }  
  46.   
  47.             Dictionary<stringobject> data = new Dictionary<stringobject>();  
  48.             data.Add("firstname", user.FirstName);  
  49.             data.Add("lastname", user.LastName);  
  50.             data.Add("email", user.Email);  
  51.             data.Add("mobile", user.Mobile);  
  52.             data.Add("password", user.Password);  
  53.   
  54.             var result = await _aPI.SignUp(data);  
  55.             Toast.MakeText(_context, result, ToastLength.Short).Show();  
  56.             return true;  
  57.         }  
  58.   
  59.         public async Task<bool> SignInUserAsync(User user)  
  60.         {  
  61.             if (String.IsNullOrEmpty(user.Email))  
  62.             {  
  63.                 Toast.MakeText(_context, "Email can not be null or empty!", ToastLength.Short).Show();  
  64.                 return false;  
  65.             }  
  66.             if (String.IsNullOrEmpty(user.Password))  
  67.             {  
  68.                 Toast.MakeText(_context, "Password can not be null or empty!", ToastLength.Short).Show();  
  69.                 return false;  
  70.             }  
  71.   
  72.             Dictionary<stringobject> data = new Dictionary<stringobject>();  
  73.             data.Add("email", user.Email);  
  74.             data.Add("password", user.Password);  
  75.             var result = await _aPI.SignIn(data);  
  76.             Toast.MakeText(_context, result, ToastLength.Short).Show();  
  77.             return true;  
  78.         }  
  79.     }  
  80. }  
Step 10 - 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.OS;  
  3. using Android.Runtime;  
  4. using Android.Support.V7.App;  
  5. using Android.Widget;  
  6. using XamarinAuth.Activities;  
  7. using XamarinAuth.API;  
  8. using XamarinAuth.Model;  
  9. using Refit;  
  10.   
  11. namespace XamarinAuth  
  12. {  
  13.     [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]  
  14.     public class MainActivity : AppCompatActivity  
  15.     {  
  16.         IAPI _aPI;  
  17.         RestAPI _restApi;  
  18.         Button btn_Signin, btn_registeration;  
  19.         EditText edt_Email, edt_Password;  
  20.         protected override void OnCreate(Bundle savedInstanceState)  
  21.         {  
  22.             base.OnCreate(savedInstanceState);  
  23.             Xamarin.Essentials.Platform.Init(this, savedInstanceState);  
  24.             // Set our view from the "main" layout resource  
  25.             SetContentView(Resource.Layout.activity_main);  
  26.             _aPI = RestService.For<IAPI>("http://10.0.2.2:3000");  
  27.   
  28.             var connection = new RestAPI(this, _aPI);  
  29.   
  30.             btn_registeration = FindViewById<Button>(Resource.Id.btn_registeration);  
  31.             btn_Signin = FindViewById<Button>(Resource.Id.btn_login);  
  32.             edt_Email = FindViewById<EditText>(Resource.Id.edt_email);  
  33.             edt_Password = FindViewById<EditText>(Resource.Id.edt_password);  
  34.   
  35.             btn_Signin.Click += async delegate   
  36.             {  
  37.                 var user = new User  
  38.                 {  
  39.                     Email = edt_Email.Text.ToString(),  
  40.                     Password = edt_Password.Text.ToString()  
  41.                 };  
  42.                 var result = await connection.SignInUserAsync(user);  
  43.                 if(result == true)  
  44.                 {  
  45.                     StartActivity(typeof(DashboardActivity));  
  46.                 }  
  47.             };  
  48.   
  49.             btn_registeration.Click += delegate   
  50.             {  
  51.                 StartActivity(typeof(RegisterActivity));  
  52.             };  
  53.         }  
  54.         public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)  
  55.         {  
  56.             Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  57.             base.OnRequestPermissionsResult(requestCode, permissions, grantResults);  
  58.         }  
  59.     }  
  60. }  
Step 11 - Permissions From Device
 
We need permission from the device because we can use the device’s INTERNET. Please add internet permission to your AndroidManifest.xml. Let's open Solution Explorer-> Properties-> AndroidManifest and let's add the code inside application tags. 
  1. <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />    
  2. <uses-permission android:name="android.permission.INTERNET" />   
User Login Testing
 
 
User Register Testing 
 


Similar Articles