DEV Community

Cover image for Xamarin Android: Create Login Using SQLite Database | iFour Technolab
Harshal Suthar
Harshal Suthar

Posted on • Originally published at ifourtechnolab.com

Xamarin Android: Create Login Using SQLite Database | iFour Technolab

Xamarin is an open-source platform for creating modern and performance applications with .NET for iOS, Android, and Windows. This pattern allows developers to write all of their business logic in one language (or reuse existing application code) but achieve original performance, look and feel on each platform.

What is SQLite?

Android SQLite is the most preferred way to store data for Android applications. For many applications, SQLite is the backbone of applications whether used directly or by a third-party wrapper. We will create it today using the Android SQLite database.

It is embedded in Android By default. Therefore, no database setup or administrative work is required.

Now let's go step by step how to create a login form in Xamarin Android

We will create this project in Visual Studio 2019, so you too should try to use the latest versions.

Step 1: Select a new project

Open Visual Studio -> Create New Project ->Android App (Xamarin)

Then click on the Next button. Note the highlight point of the image as shown in the image.We build for mobiles so mobiles need to be selected.

Image description

Step 2 : Give the project name

You can give your project the name you want. Enter the name of your project and click on the Create buttonwe have named our project SQLite which you can see in Image.

Image description

Step 3: Select template

From this, you can select whatever you want. All are templates. We only need a single page so we will select a single view app.If you need navigation you can also select the second option navigation drawer which will provide you navigation.

If you need a tab menu, you can also select the third option Tabbed App which will provide you a tab menu.

Read More: Roadmap To Xamarin Forms 5.0

If you need a blank page then select the last option which will be a blank page.Select a low level whenever possible in the minimum Android version as doing so will help you run in Low device.

Then click on OK

Image description

Now our project is ready as a normal template. Now we will add layout, NuGet package, required class, and interface.

Step 4:Add Layout

Next, go to Solution Explorer-> Project Name (SQLite) ->Resources Folder ->layout Folder. Right-click on Add -> Add item. A new dialog box will open. Select Android the layout, give a name for NewUser.xml and click Add buttonas shown in the image.

Now new Layout Page ready for Design.We will write our design code in this file.

Image description

Step 5: Add Activity Class

Now we will add an Activity class to our project in which we will write the Register Related Business Logic code.

Go to Solution Explorer-> Project Name (SQLite).Right-click on Add -> Add item. Open new a dialog boxas shown in the image. Select Activity and give name for RegisterActivity.cs. Now, add the New Activity Class.

Image description

Step 6: Add Table

Next, we need to create a database table, so we create a data layer class in the file, we will write the code to do the table, such as id, name, password, etc.

Go to Solution Explorer-> Project Name (SQLite).Right-click to Add -> Add item. Open a new dialog boxas shown in the image. Select Class, give a name for LoginTable.cs

Image description

Step 7 : NuGet package

Now we will install the NuGet package.

Go to Solution Explorer (Right -side)-> Project Name (SQLite) Right click -> Select Manage NuGet Packages.

Image description

Step 8:Install NuGet package

Once the NuGet window opens, click on Browser from the above tab and search for SQLite package and install packages.

Planning to Hire Xamarin App Development Company? Your Search ends here.

This package will help us to connect with the database as well as provide the required methodology.

Image description

Step 9 : LoginTable.cs File

Next, Go to Solution Explorer open the LoginTable.cs file, and put the below code.

namespace SQLite
{
classLoginTab
{
[PrimaryKey, AutoIncrement]
publicint id { get; set; } 
[MaxLength(50)] // Maxlength set in UserName column
publicstringuserName{ get; set; }
[MaxLength(20)] // Maxlength set in passWord column
publicstringpassWord{ get; set; }
}
}

Enter fullscreen mode Exit fullscreen mode

Step 10:MainActivity.cs File

Next, Go to Solution Explorer open the MainActivity.cs file, and put the below code.


namespace SQLite
{
publicclassMainActivity :AppCompatActivity
{
EditTextuserName;
EditText Password;
Button ncreate;
Button nsign;
protectedoverridevoidOnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
SetContentView(Resource.Layout.activity_main);
Android.Support.V7.Widget.Toolbar toolbar = FindViewById<android.support.v7.widget.toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
FloatingActionButton fab = FindViewById<floatingactionbutton>(Resource.Id.fab);
fab.Click += FabOnClick;
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Main);
btnsign = FindViewById<button>(Resource.Id.nlogin);
btncreate = FindViewById</button></floatingactionbutton></android.support.v7.widget.toolbar><button>Resource.Id.nregister);
txtusername = FindViewById<edittext>(Resource.Id.username);
txtPassword = FindViewById<edittext>(Resource.Id.pwd);
btnsign.Click += nsign_Click;
btncreate.Click += ncreate_Click;
CreateTable();
}
privatevoidncreate_Click(object send, EventArgs eve)
{
StartActivity(typeof(RegisterActivity));
}
privatevoidnsign_Click(object send, EventArgs eve)
{
try
{
stringdpPaths = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user,mydb"); 
vardbs = newSQLiteConnection(dpPaths);
var data = dbs.Table<logintable>(); 
var data11 = data.Where(x =>x.username == username.Text&&x.password == Password.Text).FirstOrDefault();
if (data11 != null)
{
Toast.MakeText(this, "Successfully Login", ToastLength.Short).Show();
}
else
{
Toast.MakeText(this, "Username or Password invalid", ToastLength.Long).Show();
}
}
catch (Exception ex)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
publicstringCreateTable()
{
var op = "";
op += "Creating Databse if it doesnt exists";
stringdpPaths = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user,mydb"); 
vardbs = newSQLiteConnection(dpPaths);
op += " Databasesucessfully Created....";
return op;
}</logintable></edittext></edittext></button>

Enter fullscreen mode Exit fullscreen mode

Step 11:RegisterActivity.cs File
Next, Go to Solution Explorer open the RegisterActivity.cs file, and put the below code.


namespace SQLite
{
EditTextusername;
EditTexttxtPassword;
Button ncreate;
[Activity(Label = "RegisterActivity")]
publicclassRegisterActivity : Activity
{
protectedoverridevoidOnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.Newuser);

btncreate = FindViewById<button>(Resource.Id.create);
txtusername = FindViewById<edittext>(Resource.Id.userName);
txtPassword = FindViewById<edittext>(Resource.Id.password);
btncreate.Click += ncreate_Click;

}
privatevoidncreate_Click(object sender, EventArgs e)
{
try
{
stringdpPaths = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), "user.db3");
vardbs = newSQLiteConnection(dpPath);
dbs.CreateTable<logintable>();
LoginTable table = newLoginTable();
table.username = username.Text;
table.password = Password.Text;
dbs.Insert(table);
Toast.MakeText(this, "Record Added…", ToastLength.Long).Show();
}
catch (Exception e)
{
Toast.MakeText(this, ex.ToString(), ToastLength.Long).Show();
}
}
}</logintable></edittext></edittext></button>


Enter fullscreen mode Exit fullscreen mode

Step 12: Output

Finally let’s see the Output

Image description

By this way, we successfully created a login form using the SQLite database.

Conclusion

In this blog, we have created a login form for an Android OS using SQLite database.We tried to explain you the step by step method where we can create a normal login form using class, method, interface, database, and package.

Top comments (0)