Introduction
Xamarin is a platform to develop cross-platform and multi-platform apps (for example, Windows phone, Android, iOS). In Xamarin platform, the code sharing concept is used. In Xamarin Studio, Visual Studio is also available. Create SQLite database with ADO.NET.
Prerequisites
- Visual Studio 2015 Update 3.
The steps, mentioned below, are required to be followed in order to create ADO.NET database in the Xamarin Android app, using Visual Studio 2015.
Step 1
Click File--> select New--> select Project. The project needs to be clicked after opening all the types of projects in Visual Studio or click (Ctrl+Shift+N).
Step 2
After opening the New Project, select Installed-->Templates-->Visual C#-->Android-->choose the Blank app (Android). Now, give your Android app; a name (Ex:sample) and give the path of your project. Afterwards, click OK.
Step 3
Now, go to Solution Explorer. In Solution Explorer, get all the files and source code in your project. Now, select Resource-->Layout-->double click to open main.axml page. You need to select the source to write XAML code. Choose the Designer Window, if you want to design it, and you can design your app.
Step 4
After opening main.axml, file will open the main page designer. You can design the page, as per your desire.
Now, delete Default hello world button, go to the source panel and you can see the button coding. You need to delete it. After deleting XAML code, now delete C# button action code. Go to MainActivity.cs page. You need to delete the button code.
Step 5
Now, go to the toolbox Window. In the toolbox Window, get all the types of the tools and controls. You need to go to the toolbox Window. Now, scroll down. You will see all the tools and controls.
You need to drag and drop the button.
Step 6
You need to drag and drop the TextView.
Step 7
You need to drag and drop the TextView.
Step 8
Now, go to the properties Window. You need to edit the button's Id value and Text Value (EX: android:id="@+id/btnCreateDB" android:text="Create Database").
Step 9
Edit the TextView's Id value and Text Value (Ex: android:id="@+id/textView1"android:text="Results").
Step 10
Also, edit the TextView's Id value (Ex: android:id="@+id/txtResults").
Step 11
In this step, go to Main.axml page Source Panel. Note, the button's Id value.and also note TextView Id values.
Main.axml
- <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1">
- <LinearLayout android:orientation="horizontal" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout1" android:layout_weight=".2" android:gravity="center">
- <Button android:text="Create Database" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnCreateDB" /> </LinearLayout>
- <LinearLayout android:orientation="vertical" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout2" android:layout_weight=".6" android:layout_marginLeft="5dp" android:layout_marginRight="5dp">
- <TextView android:text="Results" android:textAppearance="?android:attr/textAppearanceMedium" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/textView1" android:textColor="#fff" />
- <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/txtResults" android:layout_marginTop="5dp" /> </LinearLayout>
- <LinearLayout android:orientation="horizontal" android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/linearLayout3" android:layout_weight=".2" /> </LinearLayout>
Step 12 In this step, add required reference into your app.
Go to Solution Explorer-->Reference-->Right Click-->Add Reference.
Step 13 Now, select Reference required by you.
System.Data
System.DataSQLite Step 14 Now, you will see the Reference given below.
MainActivity.cs - Mono.Andriod
- Mono.Data.SQLite
- System
- System.Core
- System.Data
- System.Xml
Step 15 In this step, go to the MainActivity.cs page in Solution Explorer and add the namespace, mentioned below.
using System.Data; - using System.IO;
- using Mono.Data.Sqlite;
- using System.Runtime.InteropServices;
- using System.Threading.Tasks;
Step 16 Now, write the code given below from OnCreate() Method.in MainActivity.cs.
MainActivity.cs - protected override void OnCreate(Bundle bundle) {
- base.OnCreate(bundle);
-
- SetContentView(Resource.Layout.Main);
- var btnCreate = FindViewById < Button > (Resource.Id.btnCreateDB);
- var txtResult = FindViewById < TextView > (Resource.Id.txtResults);
- var context = btnCreate.Context;
- var docsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
- var pathToDatabase = Path.Combine(docsFolder, "db_adonet.db");
- btnCreate.Click += async delegate {
- try {
- SqliteConnection.CreateFile(pathToDatabase);
- txtResult.Text = string.Format("Database created successfully - filename = {0}\n", pathToDatabase);
- } catch (IOException ex) {
- var reason = string.Format("Unable to create the database - reason = {0}", ex.Message);
- Toast.MakeText(context, reason, ToastLength.Long).Show();
- }
- txtResult.Text += await createTable(pathToDatabase);
- };
- }
Step 17 In this step, add async Task in MainActivity.cs page and write the code, mentioned below.
MainActivity.cs - private async Task < string > createTable(string path) {
- var connectionString = string.Format("Data Source={0};Version=3;", path);
- try {
- using(var conn = new SqliteConnection((connectionString))) {
- await conn.OpenAsync();
- using(var command = conn.CreateCommand()) {
- command.CommandText = "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName ntext, LastName ntext)";
- command.CommandType = CommandType.Text;
- await command.ExecuteNonQueryAsync();
- return "Database table created successfully";
- }
- }
- } catch (Exception ex) {
- var reason = string.Format("Failed to insert into the database - reason = {0}", ex.Message);
- return reason;
- }
- }
-
- if ('this_is' == /an_example/) {
- of_beautifier();
- } else {
- var a = b ? (c % d) : e[f];
- }
Step 18 In this step, give the required permissions in your app.
Go to the Solution Explorer--> properties-->Right click-->Open.
Step 19 After opening properties options, select Android Manifest-->Required Permissions-->Check WRITE EXTERNAL_STORAGE.
Step 20 If you have an Android virtual device, run the app on it, else connect your Android phone and run the app on it.
Simply, connect your phone and go to Visual Studio. The connected phone will show up in the Run menu (Ex:LENOVO A6020a40(Android 5.1-API 22)). Click the Run option.
Output After a few seconds, the app will start running on your phone. You will see your app is successful. Now, you can click Create Database Button.
You will see the database is created successfully.
Summary
This was the process of how to create ADO.NET database in Xamarin Android app, using Visual Studio 2015.