Introduction
This blog demonstrates how to create a Login and Registration form and then save the form details in SQLite database in Xamarin Android. Finally, the post shows how to allow the user to log in once registered.
Steps
First, create new a project in Xamarin Android in Visual Studio (Ctrl+Shift+O). Select Android templates and select Android App (Xamarin) and Single View app template (it depends on our requirement).
Below are the steps we will perform:
  1. Create a UI design for 3 pages - SignUp.axml (for User Registration), Main.axml (for Login User) & Welcome.axml (for screen after login).
  2. UserDetails.cs (Strongly Typed DTO)
  3. Helper.cs (Helper Class - for DB Operation)
  4. Activities w.r.t. UI Pages - SignUp.cs (for User Registration activity), MainActivity.cs (for User Login activity) & Welcome.cs (for welcome screen activity after login).
UI Design
Create a SignUp (Registration) page.Go to Resources/Layout folder and create new Layout file (SignUp.axml) file. Once it is created, update it with 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. android:minWidth="25px"
  7. android:minHeight="25px">
  8. <EditText
  9. android:hint="Username"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. android:layout_marginLeft="20dp"
  13. android:layout_marginRight="20dp"
  14. android:id="@+id/edtusername"/>
  15. <EditText
  16. android:hint="Email"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:layout_marginLeft="20dp"
  20. android:layout_marginRight="20dp"
  21. android:id="@+id/edtEmail"
  22. />
  23. <EditText
  24. android:hint="Password"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:layout_marginLeft="20dp"
  28. android:layout_marginRight="20dp"
  29. android:id="@+id/edtpassword"
  30. android:inputType="textPassword" />
  31. <EditText
  32. android:hint="First Name"
  33. android:layout_width="match_parent"
  34. android:layout_height="wrap_content"
  35. android:layout_marginLeft="20dp"
  36. android:layout_marginRight="20dp"
  37. android:id="@+id/edtfname"/>
  38. <EditText
  39. android:hint="Last Name"
  40. android:layout_width="match_parent"
  41. android:layout_height="wrap_content"
  42. android:layout_marginLeft="20dp"
  43. android:layout_marginRight="20dp"
  44. android:id="@+id/edtlname"/>
  45. <EditText
  46. android:hint="Mobile"
  47. android:layout_width="match_parent"
  48. android:layout_height="wrap_content"
  49. android:layout_marginLeft="20dp"
  50. android:layout_marginRight="20dp"
  51. android:id="@+id/edtMobile"
  52. android:inputType="phone" />
  53. <EditText
  54. android:hint="Address"
  55. android:layout_width="match_parent"
  56. android:layout_height="wrap_content"
  57. android:layout_marginLeft="20dp"
  58. android:layout_marginRight="20dp"
  59. android:id="@+id/edtAddress"/>
  60. <EditText
  61. android:hint="Country"
  62. android:layout_width="match_parent"
  63. android:layout_height="wrap_content"
  64. android:layout_marginLeft="20dp"
  65. android:layout_marginRight="20dp"
  66. android:id="@+id/edtCountry"/>
  67. <Button
  68. android:text="Create"
  69. android:layout_width="match_parent"
  70. android:layout_height="wrap_content"
  71. android:layout_marginLeft="20dp"
  72. android:layout_marginRight="20dp"
  73. android:id="@+id/btnCreate" />
  74. <Button
  75. android:text="Back to Home"
  76. android:layout_width="match_parent"
  77. android:layout_height="wrap_content"
  78. android:layout_marginLeft="20dp"
  79. android:layout_marginRight="20dp"
  80. android:id="@+id/btnBack" />
  81. </LinearLayout>
Similarly, create new Layout file (axml) file for Login.
Login (Main.axml)
  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. android:minWidth="25px"
  7. android:minHeight="25px">
  8. <EditText
  9. android:hint="Username"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. android:layout_marginLeft="20dp"
  13. android:layout_marginRight="20dp"
  14. android:id="@+id/txtusername"/>
  15. <EditText
  16. android:hint="Password"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:layout_marginLeft="20dp"
  20. android:layout_marginRight="20dp"
  21. android:id="@+id/txtpassword"
  22. android:inputType="textPassword" />
  23. <Button
  24. android:text="Sign In"
  25. android:layout_width="match_parent"
  26. android:layout_height="wrap_content"
  27. android:layout_marginLeft="20dp"
  28. android:layout_marginRight="20dp"
  29. android:id="@+id/btnSign" />
  30. <TextView
  31. android:text="Or"
  32. android:textAppearance="?android:attr/textAppearanceMedium"
  33. android:layout_width="match_parent"
  34. android:layout_height="wrap_content"
  35. android:textColor="#000"
  36. android:gravity="center"
  37. android:id="@+id/txtOr" />
  38. <Button
  39. android:text="Register"
  40. android:layout_width="match_parent"
  41. android:layout_height="wrap_content"
  42. android:layout_marginLeft="20dp"
  43. android:layout_marginRight="20dp"
  44. android:id="@+id/btnSignUp" />
  45. </LinearLayout>
Finally, create Welcome page (Welcome.axml)
  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. android:minWidth="25px"
  7. android:minHeight="25px">
  8. <TextView
  9. android:textAppearance="?android:attr/textAppearanceMedium"
  10. android:layout_width="match_parent"
  11. android:layout_height="wrap_content"
  12. android:textColor="#000"
  13. android:gravity="left"
  14. android:id="@+id/txtWelcome" />
  15. <Button
  16. android:text="Logout"
  17. android:layout_width="match_parent"
  18. android:layout_height="wrap_content"
  19. android:layout_marginLeft="20dp"
  20. android:layout_marginRight="20dp"
  21. android:id="@+id/btnLogout" />
  22. </LinearLayout>
We have finished the first step of creating UI Design. Now we'll move to second step for creating a DTO class.
UserDetails.cs (DTO)
For registration and Log-In, we will require User information, so we will create a strongly-typed class called UserDetails. We'll use the same for storing the details in the SQLite database.
Create a new folder Common, add a new empty class file called UserDetails.cs and update the content as shown below.
  1. public class UserDetails
  2. {
  3. public string ID { get; set; }
  4. public string Username { get; set; }
  5. public string FirstName { get; set; }
  6. public string LastName { get; set; }
  7. public string Address { get; set; }
  8. public string Country { get; set; }
  9. public string Email { get; set; }
  10. public string Password { get; set; }
  11. public string Mobile { get; set; }
  12. public UserDetails() { }
  13. public UserDetails(string Id, string username, string fname,string lname,string address,string country, string email, string password, string mobile) //Constructor with all parameters
  14. {
  15. ID = Id;
  16. Username = username;
  17. FirstName = fname;
  18. LastName = lname;
  19. Address = address;
  20. Country = country;
  21. Email = email;
  22. Password = password;
  23. Mobile = mobile;
  24. }
  25. public UserDetails(string Password) //Constructor with one parameter
  26. {
  27. this.Password = Password;
  28. }
  29. }
Helper.cs (Database Helper - SQLite Operations)
We will create a Helper class for DB operation. Let's create a new folder DBHelper, add a new class file called Helper.cs and update it with contents as shown below. It is responsible for handling DBOperation (Create and Read).
Note: You may need to refer below namespaces for SQLite if you encounter reference errors.
using Android.Database;
using Android.Database.Sqlite;
  1. public class Helper : SQLiteOpenHelper
  2. {
  3. private static string _DatabaseName = "clientDatabase";
  4. public Helper(Context context) : base(context, _DatabaseName, null, 1) { }
  5. public override void OnCreate(SQLiteDatabase db)
  6. {
  7. db.ExecSQL(Helper.CreateQuery);
  8. }
  9. public override void OnUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
  10. {
  11. db.ExecSQL(Helper.DeleteQuery);
  12. OnCreate(db);
  13. }
  14. private const string TableName = "adminTable";
  15. private const string ColumnID = "id";
  16. private const string ColumnUsername = "username";
  17. private const string ColumnFirstName = "firstname";
  18. private const string ColumnLastName = "lastname";
  19. private const string ColumnAddress = "address";
  20. private const string ColumnCountry = "country";
  21. private const string ColumnPassword = "password";
  22. private const string ColumnEmail = "email";
  23. private const string ColumnMobile = "mobile";
  24. public const string CreateQuery = "CREATE TABLE " + TableName +
  25. " ( "
  26. + ColumnID + " INTEGER PRIMARY KEY,"
  27. + ColumnUsername + " TEXT,"
  28. + ColumnFirstName + " TEXT,"
  29. + ColumnLastName + " TEXT,"
  30. + ColumnAddress + " TEXT,"
  31. + ColumnCountry + " TEXT,"
  32. + ColumnPassword + " TEXT,"
  33. + ColumnEmail + " TEXT,"
  34. + ColumnMobile + " TEXT)";
  35. public const string DeleteQuery = "DROP TABLE IF EXISTS " + TableName;
  36. public void Register(Context context, UserDetails user)
  37. {
  38. SQLiteDatabase db = new Helper(context).WritableDatabase;
  39. ContentValues Values = new ContentValues();
  40. Values.Put(ColumnUsername, user.Username);
  41. Values.Put(ColumnFirstName, user.FirstName);
  42. Values.Put(ColumnLastName, user.LastName);
  43. Values.Put(ColumnCountry, user.Country);
  44. Values.Put(ColumnAddress, user.Address);
  45. Values.Put(ColumnPassword, user.Password);
  46. Values.Put(ColumnEmail, user.Email);
  47. Values.Put(ColumnMobile, user.Mobile);
  48. db.Insert(TableName, null, Values);
  49. db.Close();
  50. }
  51. public UserDetails Authenticate(Context context, UserDetails user)
  52. {
  53. SQLiteDatabase db = new Helper(context).ReadableDatabase;
  54. ICursor cursor = db.Query(TableName, new string[]
  55. { ColumnID, ColumnFirstName,ColumnLastName,ColumnAddress,ColumnCountry, ColumnUsername, ColumnPassword, ColumnEmail, ColumnMobile },
  56. ColumnUsername + "=?", new string[] { user.Username }, null, null, null);
  57. if(cursor != null && cursor.MoveToFirst() && cursor.Count > 0)
  58. {
  59. UserDetails user1 = new UserDetails(cursor.GetString(6));
  60. if (user.Password.Equals(user1.Password))
  61. return user1;
  62. }
  63. return null;
  64. }
  65. public List<UserDetails> GetUser(Context context)
  66. {
  67. List<UserDetails> users = new List<UserDetails>();
  68. SQLiteDatabase db = new Helper(context).ReadableDatabase;
  69. string[] columns = new string[] {ColumnID,ColumnUsername,ColumnFirstName,ColumnLastName,ColumnAddress,ColumnCountry,ColumnPassword,ColumnEmail,ColumnMobile };
  70. using(ICursor cursor = db.Query(TableName, columns, null, null, null, null, null))
  71. {
  72. while (cursor.MoveToNext())
  73. {
  74. users.Add(new UserDetails
  75. {
  76. ID = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnID)),
  77. Username = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnUsername)),
  78. FirstName = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnFirstName)),
  79. Country = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnCountry)),
  80. Address = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnAddress)),
  81. LastName = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnLastName)),
  82. Password = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnPassword)),
  83. Email = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnEmail)),
  84. Mobile = cursor.GetString(cursor.GetColumnIndexOrThrow(ColumnMobile))
  85. });
  86. }
  87. db.Close();
  88. return users;
  89. }
  90. }
  91. }
We have finished step 3. Now we are left with creating activity class w.r.t. Layouts (axml's.)
Activities
Finally, we will create an activity for passing the data to and from layouts-to-SQLite db. Create a folder Activities first and add the below-listed class files.
1. MainActivity..cs (For User Login Activity)
  1. [Activity(MainLauncher = true)]
  2. public class MainActivity : Activity
  3. {
  4. private EditText txtUsername, txtPassword;
  5. private Button btnSignIn, btnCreate;
  6. Helper helper;
  7. protected override void OnCreate(Bundle savedInstanceState)
  8. {
  9. base.OnCreate(savedInstanceState);
  10. // Set our view from the "main" layout resource
  11. SetContentView(Resource.Layout.Main);
  12. txtUsername = FindViewById<EditText>(Resource.Id.txtusername);
  13. txtPassword = FindViewById<EditText>(Resource.Id.txtpassword);
  14. btnCreate = FindViewById<Button>(Resource.Id.btnSignUp);
  15. btnSignIn = FindViewById<Button>(Resource.Id.btnSign);
  16. helper = new Helper(this);
  17. btnCreate.Click += delegate { StartActivity(typeof(SignUp)); };
  18. btnSignIn.Click += delegate
  19. {
  20. try
  21. {
  22. string Username = txtUsername.Text.ToString();
  23. string Password = txtPassword.Text.ToString();
  24. var user = helper.Authenticate(this,new UserDetails(null,Username,null,null,null,null,null,Password,null));
  25. if (user != null)
  26. {
  27. Toast.MakeText(this, "Login Successful", ToastLength.Short).Show();
  28. Intent intent = new Intent(this, typeof(Welcome));
  29. intent.PutExtra("UserName", Username);
  30. StartActivity(typeof(Welcome));
  31. }
  32. else
  33. {
  34. Toast.MakeText(this, "Login Unsuccessful! Please verify your Username and Password", ToastLength.Short).Show();
  35. }
  36. }
  37. catch (SQLiteException ex)
  38. {
  39. Toast.MakeText(this, ""+ex, ToastLength.Short).Show();
  40. }
  41. };
  42. }
  43. }
2. SignUp.cs ( For User Registration Activity)
  1. [Activity]
  2. public class SignUp : Activity
  3. {
  4. private EditText edtfname,edtlname,edtCountry,edtAddress, edtUsername, edtEmail, edtPassword, edtMobile;
  5. private Button btnCreate, btnBack;
  6. Helper helper;
  7. protected override void OnCreate(Bundle savedInstanceState)
  8. {
  9. base.OnCreate(savedInstanceState);
  10. // Create your application here
  11. SetContentView(Resource.Layout.SignUp);
  12. edtfname = FindViewById<EditText>(Resource.Id.edtfname);
  13. edtlname= FindViewById<EditText>(Resource.Id.edtlname);
  14. edtCountry= FindViewById<EditText>(Resource.Id.edtCountry);
  15. edtAddress= FindViewById<EditText>(Resource.Id.edtAddress);
  16. edtUsername = FindViewById<EditText>(Resource.Id.edtusername);
  17. edtPassword = FindViewById<EditText>(Resource.Id.edtpassword);
  18. edtEmail = FindViewById<EditText>(Resource.Id.edtEmail);
  19. edtMobile = FindViewById<EditText>(Resource.Id.edtMobile);
  20. btnCreate = FindViewById<Button>(Resource.Id.btnCreate);
  21. btnBack = FindViewById<Button>(Resource.Id.btnBack);
  22. helper = new Helper(this);
  23. btnBack.Click += delegate { StartActivity(typeof(MainActivity)); };
  24. btnCreate.Click += delegate
  25. {
  26. UserDetails user = new UserDetails()
  27. {
  28. FirstName = edtfname.Text,
  29. LastName=edtlname.Text,
  30. Address=edtAddress.Text,
  31. Country=edtCountry.Text,
  32. Username = edtUsername.Text,
  33. Password = edtPassword.Text,
  34. Email = edtEmail.Text,
  35. Mobile = edtMobile.Text
  36. };
  37. string username = edtUsername.Text;
  38. string password = edtPassword.Text;
  39. if(string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
  40. {
  41. Toast.MakeText(this, "Username and Password should not be empty.", ToastLength.Short).Show();
  42. }
  43. else
  44. {
  45. helper.Register(this, user);
  46. var data = helper.GetUser(this);
  47. user = data[data.Count - 1];
  48. Toast.MakeText(this, $"User {user.Username} registration successful!", ToastLength.Short).Show();
  49. Clear();
  50. Toast.MakeText(this, $"Total {data.Count} Users.", ToastLength.Short).Show();
  51. }
  52. };
  53. }
  54. void Clear()
  55. {
  56. edtfname.Text = "";
  57. edtlname.Text = "";
  58. edtAddress.Text = "";
  59. edtCountry.Text = "";
  60. edtUsername.Text = "";
  61. edtPassword.Text = "";
  62. edtMobile.Text = "";
  63. edtEmail.Text = "";
  64. }
  65. }
3. Welcome.cs (After log-in Welcome page activity)
  1. [Activity(Label = "Welcome")]
  2. public class Welcome : Activity
  3. {
  4. string loggedInUser { get; set; }
  5. private TextView txtWelcome;
  6. private Button btnLogout;
  7. protected override void OnCreate(Bundle savedInstanceState)
  8. {
  9. base.OnCreate(savedInstanceState);
  10. // Create your application here
  11. SetContentView(Resource.Layout.Welcome);
  12. txtWelcome = FindViewById<TextView>(Resource.Id.txtWelcome);
  13. txtWelcome.Text = $"Welcome {Intent.GetStringExtra("UserName") ?? "User" }";
  14. btnLogout = FindViewById<Button>(Resource.Id.btnLogout);
  15. btnLogout.Click+= delegate { StartActivity(typeof(MainActivity)); };
  16. }
  17. }
That's it! Now run the code and see the output. You should be able to Register User, Login, and Logout. And all this information is stored in the SQLite database.
Happy Coding!