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. <TextView
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:textStyle="bold"
  15. android:text="Login Page"
  16. android:textSize="25sp"
  17. android:textAlignment="center"
  18. android:textColor="@color/colorPrimary"/>
  19. <EditText
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:hint="Email"
  23. android:inputType="textEmailAddress"
  24. android:id="@+id/edt_email"/>
  25. <EditText
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"
  28. android:hint="Password"
  29. android:inputType="textPassword"
  30. android:id="@+id/edt_password"/>
  31. <LinearLayout
  32. android:orientation="horizontal"
  33. android:layout_width="match_parent"
  34. android:layout_height="wrap_content"
  35. android:weightSum="2">
  36. <Button
  37. android:layout_width="0dp"
  38. android:layout_height="wrap_content"
  39. android:layout_weight="1"
  40. android:hint="Login"
  41. android:id="@+id/btn_login"
  42. android:layout_marginTop="15dp"/>
  43. <Button
  44. android:layout_width="0dp"
  45. android:layout_height="wrap_content"
  46. android:layout_weight="1"
  47. android:hint="Register"
  48. android:id="@+id/btn_registeration"
  49. android:layout_marginTop="15dp"/>
  50. </LinearLayout>
  51. </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. <TextView
  12. android:layout_width="match_parent"
  13. android:layout_height="wrap_content"
  14. android:textStyle="bold"
  15. android:text="Register Page"
  16. android:textSize="25sp"
  17. android:textAlignment="center"
  18. android:textColor="@color/colorPrimary"/>
  19. <EditText
  20. android:layout_width="match_parent"
  21. android:layout_height="wrap_content"
  22. android:hint="First Name"
  23. android:inputType="text"
  24. android:id="@+id/edt_fname"/>
  25. <EditText
  26. android:layout_width="match_parent"
  27. android:layout_height="wrap_content"
  28. android:hint="Last Name"
  29. android:inputType="text"
  30. android:id="@+id/edt_lname"/>
  31. <EditText
  32. android:layout_width="match_parent"
  33. android:layout_height="wrap_content"
  34. android:hint="Mobile"
  35. android:inputType="text"
  36. android:id="@+id/edt_mobile"/>
  37. <EditText
  38. android:layout_width="match_parent"
  39. android:layout_height="wrap_content"
  40. android:hint="Email"
  41. android:inputType="textEmailAddress"
  42. android:id="@+id/edt_email"/>
  43. <EditText
  44. android:layout_width="match_parent"
  45. android:layout_height="wrap_content"
  46. android:hint="Password"
  47. android:inputType="textPassword"
  48. android:id="@+id/edt_password"/>
  49. <LinearLayout
  50. android:orientation="horizontal"
  51. android:layout_width="match_parent"
  52. android:layout_height="wrap_content"
  53. android:weightSum="2">
  54. <Button
  55. android:layout_width="0dp"
  56. android:layout_height="wrap_content"
  57. android:layout_weight="1"
  58. android:hint="Register"
  59. android:id="@+id/btn_register"
  60. android:layout_marginTop="15dp"/>
  61. <Button
  62. android:layout_width="0dp"
  63. android:layout_height="wrap_content"
  64. android:layout_weight="1"
  65. android:hint="Cancel"
  66. android:id="@+id/btn_cancel"
  67. android:layout_marginTop="15dp"/>
  68. </LinearLayout>
  69. </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. <TextView
  7. android:layout_marginTop="20dp"
  8. android:layout_width="match_parent"
  9. android:layout_height="wrap_content"
  10. android:textStyle="bold"
  11. android:text="Welcome To Dashboard"
  12. android:textSize="25sp"
  13. android:textAlignment="center"
  14. android:textColor="@color/colorPrimary"/>
  15. <Button
  16. android:layout_marginLeft="120dp"
  17. android:layout_width="wrap_content"
  18. android:layout_height="wrap_content"
  19. android:hint="Back To Home"
  20. android:id="@+id/btn_cancel"
  21. android:layout_marginTop="30dp"/>
  22. </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 { get; set; }
  4. public string LastName { get; set; }
  5. public string Email { get; set; }
  6. public string Password { get; set; }
  7. public string Mobile { get; set; }
  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. namespace XamarinAuth.Activities
  15. {
  16. [Activity(Label = "RegisterActivity")]
  17. public class RegisterActivity : Activity
  18. {
  19. IAPI _aPI;
  20. Button btn_register, btn_cancel;
  21. EditText edt_Email, edt_Password, edt_fname, edt_lname, edt_mobile;
  22. protected override void OnCreate(Bundle savedInstanceState)
  23. {
  24. base.OnCreate(savedInstanceState);
  25. SetContentView(Resource.Layout.activity_register);
  26. // Create your application here
  27. _aPI = RestService.For<IAPI>("http://10.0.2.2:3000");
  28. var connection = new RestAPI(this, _aPI);
  29. btn_register = FindViewById<Button>(Resource.Id.btn_register);
  30. btn_cancel= FindViewById<Button>(Resource.Id.btn_cancel);
  31. edt_lname = FindViewById<EditText>(Resource.Id.edt_lname);
  32. edt_mobile = FindViewById<EditText>(Resource.Id.edt_mobile);
  33. edt_fname = FindViewById<EditText>(Resource.Id.edt_fname);
  34. edt_Email = FindViewById<EditText>(Resource.Id.edt_email);
  35. edt_Password = FindViewById<EditText>(Resource.Id.edt_password);
  36. btn_cancel.Click += delegate { StartActivity(typeof(MainActivity)); };
  37. btn_register.Click += async delegate
  38. {
  39. var user = new User
  40. {
  41. FirstName = edt_fname.Text.ToString(),
  42. LastName = edt_lname.Text.ToString(),
  43. Mobile = edt_mobile.Text.ToString(),
  44. Email = edt_Email.Text.ToString(),
  45. Password = edt_Password.Text.ToString(),
  46. };
  47. var result = await connection.RegisterUserAsync(user);
  48. if(result == true)
  49. {
  50. StartActivity(typeof(MainActivity));
  51. }
  52. };
  53. }
  54. }
  55. }
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. namespace XamarinAuth.Activities
  5. {
  6. [Activity(Label = "DashboardActivity")]
  7. public class DashboardActivity : Activity
  8. {
  9. Button btn_backToHome;
  10. protected override void OnCreate(Bundle savedInstanceState)
  11. {
  12. base.OnCreate(savedInstanceState);
  13. SetContentView(Resource.Layout.activity_dashboard);
  14. // Create your application here
  15. btn_backToHome = FindViewById<Button>(Resource.Id.btn_cancel);
  16. btn_backToHome.Click += delegate
  17. {
  18. StartActivity(typeof(MainActivity));
  19. };
  20. }
  21. }
  22. }
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. namespace XamarinAuth.API
  5. {
  6. public interface IAPI
  7. {
  8. [Post("/login")]
  9. Task<string> SignIn([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
  10. [Post("/register")]
  11. Task<string> SignUp([Body(BodySerializationMethod.UrlEncoded)] Dictionary<string, object> data);
  12. }
  13. }
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. namespace XamarinAuth.API
  8. {
  9. public class RestAPI
  10. {
  11. IAPI _aPI;
  12. Context _context;
  13. public RestAPI(Context context, IAPI aPI)
  14. {
  15. _aPI = aPI;
  16. _context = context;
  17. }
  18. public async Task<bool> RegisterUserAsync(User user)
  19. {
  20. if (String.IsNullOrEmpty(user.FirstName))
  21. {
  22. Toast.MakeText(_context, "FirstName can not be null or empty!", ToastLength.Short).Show();
  23. return false;
  24. }
  25. if (String.IsNullOrEmpty(user.LastName))
  26. {
  27. Toast.MakeText(_context, "LastName can not be null or empty!", ToastLength.Short).Show();
  28. return false;
  29. }
  30. if (String.IsNullOrEmpty(user.Email))
  31. {
  32. Toast.MakeText(_context, "Email can not be null or empty!", ToastLength.Short).Show();
  33. return false;
  34. }
  35. if (String.IsNullOrEmpty(user.Mobile))
  36. {
  37. Toast.MakeText(_context, "Mobile Number can not be null or empty!", ToastLength.Short).Show();
  38. return false;
  39. }
  40. if (String.IsNullOrEmpty(user.Password))
  41. {
  42. Toast.MakeText(_context, "Password can not be null or empty!", ToastLength.Short).Show();
  43. return false;
  44. }
  45. Dictionary<string, object> data = new Dictionary<string, object>();
  46. data.Add("firstname", user.FirstName);
  47. data.Add("lastname", user.LastName);
  48. data.Add("email", user.Email);
  49. data.Add("mobile", user.Mobile);
  50. data.Add("password", user.Password);
  51. var result = await _aPI.SignUp(data);
  52. Toast.MakeText(_context, result, ToastLength.Short).Show();
  53. return true;
  54. }
  55. public async Task<bool> SignInUserAsync(User user)
  56. {
  57. if (String.IsNullOrEmpty(user.Email))
  58. {
  59. Toast.MakeText(_context, "Email can not be null or empty!", ToastLength.Short).Show();
  60. return false;
  61. }
  62. if (String.IsNullOrEmpty(user.Password))
  63. {
  64. Toast.MakeText(_context, "Password can not be null or empty!", ToastLength.Short).Show();
  65. return false;
  66. }
  67. Dictionary<string, object> data = new Dictionary<string, object>();
  68. data.Add("email", user.Email);
  69. data.Add("password", user.Password);
  70. var result = await _aPI.SignIn(data);
  71. Toast.MakeText(_context, result, ToastLength.Short).Show();
  72. return true;
  73. }
  74. }
  75. }
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. namespace XamarinAuth
  11. {
  12. [Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
  13. public class MainActivity : AppCompatActivity
  14. {
  15. IAPI _aPI;
  16. RestAPI _restApi;
  17. Button btn_Signin, btn_registeration;
  18. EditText edt_Email, edt_Password;
  19. protected override void OnCreate(Bundle savedInstanceState)
  20. {
  21. base.OnCreate(savedInstanceState);
  22. Xamarin.Essentials.Platform.Init(this, savedInstanceState);
  23. // Set our view from the "main" layout resource
  24. SetContentView(Resource.Layout.activity_main);
  25. _aPI = RestService.For<IAPI>("http://10.0.2.2:3000");
  26. var connection = new RestAPI(this, _aPI);
  27. btn_registeration = FindViewById<Button>(Resource.Id.btn_registeration);
  28. btn_Signin = FindViewById<Button>(Resource.Id.btn_login);
  29. edt_Email = FindViewById<EditText>(Resource.Id.edt_email);
  30. edt_Password = FindViewById<EditText>(Resource.Id.edt_password);
  31. btn_Signin.Click += async delegate
  32. {
  33. var user = new User
  34. {
  35. Email = edt_Email.Text.ToString(),
  36. Password = edt_Password.Text.ToString()
  37. };
  38. var result = await connection.SignInUserAsync(user);
  39. if(result == true)
  40. {
  41. StartActivity(typeof(DashboardActivity));
  42. }
  43. };
  44. btn_registeration.Click += delegate
  45. {
  46. StartActivity(typeof(RegisterActivity));
  47. };
  48. }
  49. public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
  50. {
  51. Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  52. base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  53. }
  54. }
  55. }
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