Documentos de Académico
Documentos de Profesional
Documentos de Cultura
Guides
Xamarin.Forms
Working with...
Sample Code:
Todo Sample
Related Samples:
Xamarin.Forms Samples
Xamarin.Forms apps can easily access local SQLite databases, using NuGets with PCL
solutions and compiler directives with Shared Projects.
Overview
This article describes how Xamarin.Forms applications can read and write data to a local
SQLite database using the SQLite.Net database layer. The approach for incorporating
SQLite.Net differs depending on the project template you select:
PCL Solutions PCL solutions can take advantage of the SQLite.NET PCL NuGet
packages to easily incorporate database operations into the shared code by
referencing the SQLite classes that ship in the NuGet. The Xamarin.Forms
DependencyService is used to create the platformspecific SQLite connection that is
Sample Code
The sample on GitHub is a simple Todolist application, and includes both PCL and
Shared Project examples. These screenshots show how the sample appears on each
platform:
The SQLite database engine is builtin to the iOS and Android operating systems. To
add SQLite support to Windows Phone projects follow the instructions at the end of
this article.
Use NuGet's search function to find SQLite.Net PCL and install the package as shown:
There are a number of NuGet packages with similar names, the correct package has these
attributes:
Created by: Frank A. Krueger
Id: sqlitenetpcl
NuGet link: sqlitenetpcl
Once the reference has been added, write an Interface to abstract any platformspecific
functionality. For SQLite.Net the only platformspecific work required is to determine the
location of the database file and create a connection. The interface used in the sample has
a single method defined:
publicinterfaceISQLite{
SQLiteConnectionGetConnection();
}
Once the interface has been defined, use the DependencyService to obtain an
implementation and get a valid SQLite database connection note that we have not
implemented this interface yet, that is covered in the following sections. The sample calls
the implementation in the TodoItemDatabase constructor:
publicTodoItemDatabase(){
database=DependencyService.Get<ISQLite>().GetConnection();
database.CreateTable<TodoItem>();
}
The use of locks has been ommitted from the above code for clarity. See the sample
code itself for a simple approach to preventing concurrency issues by using a lock.
All the the data access code is written in the PCL library to be shared across all platforms.
Only the initial database setup requires platformspecific work, as outlined in the
following sections.
iOS Project
To configure the Xamarin.iOS application, add the same NuGet package to the iOS
project. This screenshot shows the NuGet window:
The only code required is the ISQLite implementation that determines the data file path
and creates a new connection. The following code places the SQLite database file in the
Library folder within the application's sandbox. See the iOS Working with the File System
documentation for more information on the different directories that are available for
storage.
[assembly:Dependency(typeof(SQLite_iOS))]
//...
publicclassSQLite_iOS:ISQLite{
publicSQLite_iOS(){}
publicSQLite.SQLiteConnectionGetConnection()
{
varsqliteFilename="TodoSQLite.db3";
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder.
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfolder
varpath=Path.Combine(libraryPath,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}
Note that the code includes the assembly:Dependency atttribute so that this
implementation is discoverable by the DependencyService.
Android Project
Add the same SQLite.Net PCL library to the Android project, as shown in this NuGet
window screenshot:
Once this reference has been added, the only code required is the ISQLite
implementation that determines the data file path and creates a new connection.
[assembly:Dependency(typeof(SQLite_Android))]
//...
publicclassSQLite_Android:ISQLite{
publicSQLite_Android(){}
publicSQLite.SQLiteConnectionGetConnection(){
varsqliteFilename="TodoSQLite.db3";
stringdocumentsPath=System.Environment.GetFolderPath(System.Environment.
varpath=Path.Combine(documentsPath,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}
been added via the SQLite for Windows Phone Extension following these
instructions.
Once the SQLite Extension has been added, add the SQLite.Net PCL NuGet to the
Windows Phone project. This screenshot shows the package in the NuGet window.
Once it has been added to the project, the only code required is the ISQLite
implementation that creates a new connection using a valid database file path. The code
below uses the Windows.Storage API to determine the default file location.
[assembly:Dependency(typeof(SQLite_WinPhone))]
//...
publicclassSQLite_WinPhone:ISQLite{
publicSQLite_WinPhone(){}
publicSQLite.SQLiteConnectionGetConnection(){
varsqliteFilename="TodoSQLite.db3";
stringpath=Path.Combine(ApplicationData.Current.LocalFolder.Path,sqliteFilename);
//Createtheconnection
varconn=newSQLite.SQLiteConnection(path);
//Returnthedatabaseconnection
returnconn;
}}
Shared Project
First, add the SQLite.cscode from GitHub to the Shared Project.
Because the Shared Project code is treated as part of each individual application project,
the TodoItemDatabase class can take advantage of compiler directives to perform platform
specific operations while sharing the remainder of the code in the class.
The only platformspecific code required is the calculation of the file path to store the
SQLite data file. This has been implemented in the sample using a private property that
encapsulates the code required for all platforms, as shown below:
stringDatabasePath{
get{
varsqliteFilename="TodoSQLite.db3";
#if__IOS__
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder
stringlibraryPath=Path.Combine(documentsPath,"..","Library");//Libraryfol
varpath=Path.Combine(libraryPath,sqliteFilename);
#else
#if__ANDROID__
stringdocumentsPath=Environment.GetFolderPath(Environment.SpecialFolder
varpath=Path.Combine(documentsPath,sqliteFilename);
#else
//WinPhone
varpath=Path.Combine(ApplicationData.Current.LocalFolder.Path,sqliteFilename);
#endif
#endif
returnpath;
}
}
The remainder of the class is 100% shared across all platforms and is also the exact same
code that is used in the PCL sample.
publicIEnumerable<TodoItem>GetItems(){
return(fromiindatabase.Table<TodoItem>()selecti).ToList();
}
publicIEnumerable<TodoItem>GetItemsNotDone()
{
returndatabase.Query<TodoItem>("SELECT*FROM[TodoItem]WHERE[Done]=0");
}
publicTodoItemGetItem(intid)
{
returndatabase.Table<TodoItem>().FirstOrDefault(x=>x.ID==id);
}
publicintDeleteItem(intid)
{
returndatabase.Delete<TodoItem>(id);
}
The use of locks has been ommitted from the above code for clarity. See the sample
itself for a simple approach to preventing concurrency issues by using a lock.
Windows Phone does not include the SQLite database engine by default, so you need to
ship it with your application. Follow these steps to add SQLite to a Windows Phone
application:
First, download the Precompiled Binaries for Windows Phone 8VISX download from the
SQLite website. The relevant section of the SQLite download page is shown here:
Once downloaded, doubleclick to install the Visual Studio extension. After it's installed
and Visual Studio has been restarted, rightclick the Xamarin.Forms Windows Phone
project and choose Add Reference....
In the Reference Manager select the Windows Phone SDK 8.0 section on the left, then tick
SQLite for Windows Phone from the Extensions list. If the SQLite option is not shown, the
SQLite VISX has not installed correctly or Visual Studio needs to be restarted.
The Windows Phone project will now have SQLite listed in the project References. This
provides SQLite database support equivalent to the iOS and Android platforms. Once this
has been installed in a Windows Phone project, return to either the PCL or Shared Project
instructions above.
For additional information on installing SQLite database support on Windows Phone, read
the Nokia docs or this helpful blog post.
Summary
Xamarin.Forms can easily support databasedriven applications using the SQLite database
engine that is builtin to iOS and Android, and which can easily be added to Windows
Phone. SQLite.Net makes it easy to load and save objects in shared code.
Previous
Files
Next
Behaviors
+1 855 9262746
Sitemap
Privacy policy
hello@xamarin.com
2016 Xamarin Inc.