Sie sind auf Seite 1von 14

12,255,491 members 58,031 online

articles

Q&A

forums

Sign in

lounge

Searchforarticles,questions,tips

SQLite with Xamarin Forms Step by Step guide


S RaviKumar2012, 1 May 2016

CPOL

Rate this:

4.11 2 votes
In many mobile applications it’s a requirement to store data locally and for that purpose we use databases with the
applications. The type of database [...]
In many mobile applications its a requirement to store data locally and for that purpose we use databases with the
applications. The type of database to use mainly depends upon the requirement of the application, but in most of MIS
Management Information Systems based application relational databases are used for this purpose.
The most commonly used relational database with Xamarin Forms is SQLite. It is the best suited relational database for mobile
applications as it has very small footprint. This article will be an step by step guide on how to use a SQLite database with a
Xamarin Forms application.We will be using the database to persist employee data. The structure of the database will be like
following Diagram:

Step1: create a new project in Xamarin/Visual Studio see this article for steps. Name it as . There is no out of box tool
available in Xamarin Forms, So we will be using a third party plugin for this purpose and the most popular plugin is SQLite.Net
PCL created by oysteinkrog.
Step2: In order to use SQLite.NetPCL plugin, add the nuget package of the plugin to each project of the solution. In Visual
Studio this can be done by right click on the solution and selecting Manage NuGet Packages for Solution option. Which will
give following screen:

In case of Xamarin Studio, you will have to individually add the NuGet package by right clicking on the Packages folder and
selecting Add Packages option on each project.
Even tough the SQLite.NetPCL package will provide us the functionality of manipulating the SQLite database, it cant
automatically initialize the database connection object as the location of the database file varies on different platforms. So in
order to solve this issue we will use dependency service to load the database file in connection object.
Step3: Create a blank interface with one method signature like following code
Hide Copy Code

usingSQLite.Net;
namespaceSQLiteEx
{
publicinterfaceISQLite
{
SQLiteConnectionGetConnection();
}
}
Step4: Create Class file named SQLiteService implementing ISQLite interface and Write the implementation of this
GetConnection in every platform specific code like following given codes:
For new database: When we are creating a database in the application itself for the first time then following code will
be used.
Android:
Hide Shrink

usingSystem;
usingXamarin.Forms;
usingSQLiteEx.Droid;

Copy Code

usingSystem.IO;
[assembly:Dependency(typeof(SqliteService))]
namespaceSQLiteEx.Droid
{
publicclassSqliteService:ISQLite
{
publicSqliteService(){}
#regionISQLiteimplementation
publicSQLite.Net.SQLiteConnectionGetConnection()
{
varsqliteFilename="SQLiteEx.db3";
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder.Personal);//
Documentsfolder
varpath=Path.Combine(documentsPath,sqliteFilename);
Console.WriteLine(path);
if(!File.Exists(path))File.Create(path);
varplat=newSQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
varconn=newSQLite.Net.SQLiteConnection(plat,path);
//Returnthedatabaseconnection
returnconn;
}
#endregion
}
}
iOS:
Hide Shrink

Copy Code

usingSQLiteEx.iOS;
usingSystem;
usingSystem.IO;
usingXamarin.Forms;
[assembly:Dependency(typeof(SqliteService))]
namespaceSQLiteEx.iOS
{
publicclassSqliteService:ISQLite
{
publicSqliteService()
{
}
#regionISQLiteimplementation
publicSQLite.Net.SQLiteConnectionGetConnection()
{
varsqliteFilename="SQLiteEx.db3";
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder.Personal);//
Documentsfolder
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfolder
varpath=Path.Combine(libraryPath,sqliteFilename);
//Thisiswherewecopyintheprepopulateddatabase
Console.WriteLine(path);
if(!File.Exists(path))
{
File.Create(path);
}
varplat=newSQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
varconn=newSQLite.Net.SQLiteConnection(plat,path);

//Returnthedatabaseconnection
returnconn;
}
#endregion
}
}
For PreCreated Database: In some application scenarios there may be a requirement that the database is prepopulated with
some data and we are going to use the same in the application. In such scenarios first copy the database file at following
mentioned locations in platform specific project and then use following code in SQLiteService Class
Android:
Copy the database file in Resources\Raw folder of Android platform project.
Hide Shrink

Copy Code

usingSystem;
usingXamarin.Forms;
usingSQLiteEx.Droid;
usingSystem.IO;
[assembly:Dependency(typeof(SqliteService))]
namespaceSQLiteEx.Droid
{

publicclassSqliteService:ISQLite{

publicSqliteService(){}

#regionISQLiteimplementation

publicSQLite.Net.SQLiteConnectionGetConnection()

varsqliteFilename="SQLiteEx.db3";

stringdocumentsPath=System.Environment.GetFolderPath
(System.Environment.SpecialFolder.Personal);//Documentsfolder

varpath=Path.Combine(documentsPath,sqliteFilename);

NAME###

//Thisiswherewecopyintheprepopulateddatabase
Console.WriteLine(path);
if(!File.Exists(path))
{

vars=Forms.Context.Resources.OpenRawResource(Resource.Raw.APGameDb);//RESOURCE

//createawritestream

FileStreamwriteStream=newFileStream(path,FileMode.OpenOrCreate,
FileAccess.Write);

//writetothestream

ReadWriteStream(s,writeStream);

varplat=newSQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
varconn=newSQLite.Net.SQLiteConnection(plat,path);

//Returnthedatabaseconnection

returnconn;
}
#endregion

///
<summary>

///helpermethodtogetthedatabaseoutof/raw/andintotheuserfilesystem

///</summary>

voidReadWriteStream(StreamreadStream,StreamwriteStream)
{

intLength=256;

Byte[]buffer=newByte[Length];

intbytesRead=readStream.Read(buffer,0,Length);

//writetherequiredbytes

while(bytesRead>0)

writeStream.Write(buffer,0,bytesRead);

bytesRead=readStream.Read(buffer,0,Length);

readStream.Close();

writeStream.Close();
}

iOS:
Copy the database file in Resources folder of Android platform project.
Hide Shrink

Copy Code

usingSQLiteEx.iOS;
usingSystem;
usingSystem.IO;
usingXamarin.Forms;
[assembly:Dependency(typeof(SqliteService))]
namespaceSQLiteEx.iOS
{
publicclassSqliteService:ISQLite
{
publicSqliteService()
{
}
#regionISQLiteimplementation
publicSQLite.Net.SQLiteConnectionGetConnection()
{
varsqliteFilename="SQLiteEx.db3";
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder.Personal);//
Documentsfolder
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfolder
varpath=Path.Combine(libraryPath,sqliteFilename);
//Thisiswherewecopyintheprepopulateddatabase
Console.WriteLine(path);
if(!File.Exists(path))
{
File.Copy(sqliteFilename,path);
}
varplat=newSQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS();
varconn=newSQLite.Net.SQLiteConnection(plat,path);
//Returnthedatabaseconnection
returnconn;
}
#endregion
}
}
Step5: Create a class in PCL project named as DataAccess. This class will contain all the data access codes for the application.

The code of the class is as follows:


Hide Shrink

Copy Code

usingSQLite.Net;
usingXamarin.Forms;
namespaceSQLiteEx
{
publicclassDataAccess
{
SQLiteConnectiondbConn;
publicDataAccess()
{
dbConn=DependencyService.Get<ISQLite>().GetConnection();
//createthetable(s)
dbConn.CreateTable<Employee>();
}
publicList<Employee>GetAllEmployees()
{
returndbConn.Query<Employee>("Select*From[Employee]");
}
publicintSaveEmployee(EmployeeaEmployee)
{
returndbConn.Insert(aEmployee);
}
publicintDeleteEmployee(EmployeeaEmployee)
{
returndbConn.Delete(aEmployee);
}
publicintEditEmployee(EmployeeaEmployee)
{
returndbConn.Update(aEmployee);
}
}
}
As it can be seen from the code above that the application is using dependency service to fetch the database and create the
connection object in the constructor of the class which will be used in order to manipulate the data.Secondly the code to
create tables are there in constructor also, this we will have to give even if we are using a precreated database as the method
automatically checks for the table in database and create it if not present.
Step6: Create the Plain Old CLR Object POCO classes for the tables present in the database. For Example Employee class
for the above given tables in DataAccess class.
Employee:
Hide Copy Code

usingSQLite.Net.Attributes;
usingSystem;
namespaceSQLiteEx
{
publicclassEmployee
{
[PrimaryKey,AutoIncrement]
publiclongEmpId
{get;set;}
[NotNull]
publicstringEmpName
{get;set;}
publicstringDesignation
{get;set;}
publicstringDepartment
{get;set;}
publicstringQualification

{get;set;}
}
}
Step7: Create the static object property of DataAccess in App class like following code. This will enable us to use manipulate
the data from any screen of the application.
Hide Shrink

Copy Code

usingXamarin.Forms;
usingXamarin.Forms.Xaml;
[assembly:XamlCompilation(XamlCompilationOptions.Compile)]
namespaceSQLiteEx
{
publicclassApp:Application
{
staticDataAccessdbUtils;
publicApp()
{
//Therootpageofyourapplication
MainPage=newNavigationPage(newManageEmployee());
}
publicstaticDataAccessDAUtil
{
get
{
if(dbUtils==null)
{
dbUtils=newDataAccess();
}
returndbUtils;
}
}
protectedoverridevoidOnStart()
{
//Handlewhenyourappstarts
}
protectedoverridevoidOnSleep()
{
//Handlewhenyourappsleeps
}
protectedoverridevoidOnResume()
{
//Handlewhenyourappresumes
}
}
}
This completes the basic structure of application using a SQLite database to persist data of the application.
Now lets create the screens of our sample application to see the CRUD operation code.The Application will contain following
screens:
1. Manage Employees
2. Add Employee
3. Show Employee Details
4. Edit Employee
Manage Employees: This screen is the home screen of the application, it will show the current list of Employees and give an
option to add new employee, view the details of the Employee and manage departments. The XAML code of this page will be
like :

Hide Shrink

Copy Code

<?xmlversion="1.0"encoding="utf8"?>
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="SQLiteEx.ManageEmployee"Title="ManageEmployees">
<ContentPage.Padding>
<OnPlatformx:TypeArguments="Thickness"iOS="0,20,0,0"/>
</ContentPage.Padding>
<ContentPage.Content>
<ListViewx:Name="lstData"HasUnevenRows="false"Header="HeaderValue"Footer="Footer"
ItemSelected="OnSelection">
<ListView.HeaderTemplate>
<DataTemplate>
<StackLayoutOrientation="Horizontal"BackgroundColor="Blue"Padding="5,5,5,5">
<LabelText="Name"FontSize="Medium"FontAttributes="Bold"TextColor="White"/>
<LabelText="Designation"FontSize="Medium"FontAttributes="Bold"TextColor="White"/>
<LabelText="Department"FontSize="Medium"FontAttributes="Bold"TextColor="White"/>
</StackLayout>
</DataTemplate>
</ListView.HeaderTemplate>
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayoutOrientation="Horizontal"Padding="5,5,5,5">
<LabelText="{BindingEmpName}"FontSize="Medium"/>
<LabelText="{BindingDesignation}"FontSize="Medium"/>
<LabelText="{BindingDepartment}"FontSize="Medium"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
<ListView.FooterTemplate>
<DataTemplate>
<StackLayoutOrientation="Horizontal"Padding="5,5,5,5">
<ButtonText="AddNewEmployee"Clicked="OnNewClicked"/>
</StackLayout>
</DataTemplate>
</ListView.FooterTemplate>
</ListView>
</ContentPage.Content>
</ContentPage>
As per the above XAML, the application executes OnSelection method on ItemSelected event of list to show the detailed
employee information, OnNewClicked method on Clicked event of Add New Employee button. The code behind of this page
will contain following code.
Hide Shrink

usingSystem;
usingXamarin.Forms;
namespaceSQLiteEx
{
publicpartialclassManageEmployee:ContentPage
{
publicManageEmployee()
{
InitializeComponent();
varvList=App.DAUtil.GetAllEmployees();
lstData.ItemsSource=vList;
}
voidOnSelection(objectsender,SelectedItemChangedEventArgse)
{

Copy Code

if(e.SelectedItem==null)
{
return;
//ItemSelectediscalledondeselection,
//whichresultsinSelectedItembeingsettonull
}
varvSelUser=(Employee)e.SelectedItem;
Navigation.PushAsync(newShowEmplyee(vSelUser));
}
publicvoidOnNewClicked(objectsender,EventArgsargs)
{
Navigation.PushAsync(newAddEmployee());
}
}
}
Add Employee: As the name suggests this page will be used for adding a new employee and will be called upon click of Add
New Employee button on Manage Employee page. The XAML code of this page will be like:
Hide Copy Code

<?xmlversion="1.0"encoding="utf8"?>
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="SQLiteEx.AddEmployee"Title="AddNew
Employee">
<ContentView.Content>

<TableViewIntent="Settings"BackgroundColor="White">

<TableRoot>

<TableSectionTitle="AddNewEmployee">

<EntryCellx:Name="txtEmpName"Label="EmployeeName"Keyboard="Text"/>

<EntryCellx:Name="txtDesign"Label="Designation"Keyboard="Text"/>

<EntryCellx:Name="txtDepartment"Label="Department"Keyboard="Text"/>

<EntryCellx:Name="txtQualification"Label="Qualification"Keyboard="Text"
/>

<ViewCell>

<ContentViewPadding="0,0">
<ContentView.Padding>
<OnPlatformx:TypeArguments="Thickness"iOS="10,0"WinPhone="0,15,0,0"/>
</ContentView.Padding>
<ContentView.Content>
<ButtonBackgroundColor="#fd6d6d"Text="Save"TextColor="White"
Clicked="OnSaveClicked"/>
</ContentView.Content>
</ContentView>

</ViewCell>

</TableSection>

</TableRoot>

</TableView>
</ContentView.Content>
</ContentPage>
The code behind of this page will contain following code:
Hide Copy Code

usingSystem;
usingXamarin.Forms;
namespaceSQLiteEx
{
publicpartialclassAddEmployee:ContentPage
{
publicAddEmployee()
{
InitializeComponent();

}
publicvoidOnSaveClicked(objectsender,EventArgsargs)
{
varvEmployee=newEmployee()
{
EmpName=txtEmpName.Text,
Department=txtDepartment.Text,
Designation=txtDesign.Text,
Qualification=txtQualification.Text
};
App.DAUtil.SaveEmployee(vEmployee);
Navigation.PushAsync(newManageEmployee());
}
}
}
Show Employee Details: As the name suggests, this page will be used to show the complete details of the employee and also
will have the option to invoke Edit Employee page and Delete Employee to delete the details of employee from database. The
XAML code of this page is like:
Hide Shrink

Copy Code

<?xmlversion="1.0"encoding="utf8"?>
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="SQLiteEx.ShowEmplyee"Title="View
Employee">
<ContentView.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
<RowDefinitionHeight="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinitionWidth="10"/>
<ColumnDefinitionWidth="*"/>
<ColumnDefinitionWidth="*"/>
<ColumnDefinitionWidth="10"/>
</Grid.ColumnDefinitions>
<LabelGrid.Row="0"Grid.Column="0"Grid.ColumnSpan="2"Text="EmployeeDetails"/>
<LabelGrid.Row="1"Grid.Column="1"Text="Name"/>
<LabelGrid.Row="1"Grid.Column="2"Text="{BindingEmpName}"/>
<LabelGrid.Row="2"Grid.Column="1"Text="Designation"/>
<LabelGrid.Row="2"Grid.Column="2"Text="{BindingDesignation}"/>
<LabelGrid.Row="3"Grid.Column="1"Text="Department"/>
<LabelGrid.Row="3"Grid.Column="2"Text="{BindingDepartment}"/>
<LabelGrid.Row="4"Grid.Column="1"Text="Qualification"/>
<LabelGrid.Row="4"Grid.Column="2"Text="{BindingQualification}"/>
<ButtonGrid.Row="5"Grid.Column="1"Text="EditDetails"Clicked="OnEditClicked"/>
<ButtonGrid.Row="5"Grid.Column="2"Text="Delete"Clicked="OnDeleteClicked"/>
</Grid>
</ContentView.Content>
</ContentPage>
And the code behind of this page will contain following code:
Hide Shrink

Copy Code

usingSystem;
usingXamarin.Forms;
namespaceSQLiteEx
{
publicpartialclassShowEmplyee:ContentPage
{
EmployeemSelEmployee;
publicShowEmplyee(EmployeeaSelectedEmp)
{
InitializeComponent();
mSelEmployee=aSelectedEmp;
BindingContext=mSelEmployee;
}
publicvoidOnEditClicked(objectsender,EventArgsargs)
{
Navigation.PushAsync(newEditEmployee(mSelEmployee));
}
publicasyncvoidOnDeleteClicked(objectsender,EventArgsargs)
{
boolaccepted=awaitDisplayAlert("Confirm","AreyouSure?","Yes","No");
if(accepted)
{
App.DAUtil.DeleteEmployee(mSelEmployee);
}
awaitNavigation.PushAsync(newManageEmployee());
}
}
}
Edit Employee: As the name suggests, this page will be used to edit the details of the employee. The XAML code of this page
is like:
Hide Shrink

Copy Code

<?xmlversion="1.0"encoding="utf8"?>
<ContentPagexmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"x:Class="SQLiteEx.EditEmployee"Title="Edit
Employee">
<ContentView.Content>
<TableViewIntent="Settings"BackgroundColor="White">
<TableRoot>
<TableSectionTitle="EditEmployee">
<EntryCellx:Name="txtEmpName"Label="EmployeeName"Text="{BindingEmpName}"
Keyboard="Text"/>
<EntryCellx:Name="txtDesign"Label="Designation"Text="{BindingDesignation}"
Keyboard="Text"/>
<EntryCellx:Name="txtDepartment"Label="Department"Text="{BindingDepartment}"
Keyboard="Text"/>
<EntryCellx:Name="txtQualification"Label="Qualification"Text="{BindingQualification}"
Keyboard="Text"/>
<ViewCell>
<ContentViewPadding="0,0">
<ContentView.Padding>
<OnPlatformx:TypeArguments="Thickness"iOS="10,0"WinPhone="0,15,0,0"/>
</ContentView.Padding>
<ContentView.Content>
<ButtonBackgroundColor="#fd6d6d"Text="Save"TextColor="White"
Clicked="OnSaveClicked"/>
</ContentView.Content>
</ContentView>
</ViewCell>
</TableSection>

</TableRoot>
</TableView>
</ContentView.Content>
</ContentPage>
And the code behind of this page will contain following code:
Hide Copy Code

usingSystem;
usingXamarin.Forms;
namespaceSQLiteEx
{
publicpartialclassEditEmployee:ContentPage
{
EmployeemSelEmployee;
publicEditEmployee(EmployeeaSelectedEmp)
{
InitializeComponent();
mSelEmployee=aSelectedEmp;
BindingContext=mSelEmployee;
}
publicvoidOnSaveClicked(objectsender,EventArgsargs)
{
mSelEmployee.EmpName=txtEmpName.Text;
mSelEmployee.Department=txtDepartment.Text;
mSelEmployee.Designation=txtDesign.Text;
mSelEmployee.Qualification=txtQualification.Text;
App.DAUtil.EditEmployee(mSelEmployee);
Navigation.PushAsync(newManageEmployee());
}
}
}
As mentioned earlier in the article, this article contains step by step guide to use SQLite database in Xamarin Forms mobile
application. The example code of this article can be found at GitHub. Let me know if I has missed anything or have any
suggestions.
Happy Coding
Reference : Xamarin Forms Documentation.

License
This article, along with any associated source code and files, is licensed under The Code Project Open License CPOL

Share
EMAIL

About the Author

TWITTER

S RaviKumar2012
Architect
India
Hi There, I am an IT professional with 14 years of experience in architecting, designing and building IT solutions for complex
business needs in form of mobile & web applications using Microsoft technologies. Currently working in an multinational
company in India as Solutions Architect. The articles here are sourced from my blog : http://err2solution.com/

You may also be interested in...


WPF/Silverlight: Step By Step Guide to MVVM

Microsoft Guide to Building Great Apps

Step by Step Guide to Delicious OAuth API

SAPrefs - Netscape-like Preferences Dialog

Step by Step Guide to Trace the ASP.NET


Application for Beginners

Generate and add keyword variations using


AdWords API

Comments and Discussions

You must Sign In to use this message board.


Search Comments

Go

There are no messages in this forum

Permalink | Advertise | Privacy | Terms of Use | Mobile


Web02 | 2.8.160426.1 | Last Updated 2 May 2016

Seleccionar idioma
Layout: fixed | fluid

Article Copyright 2016 by S RaviKumar2012


Everything else Copyright CodeProject, 19992016

Das könnte Ihnen auch gefallen