Use SQLite.NET In Xamarin.Forms

Using SQLite in Xamarin.Forms is easy. In this blog post let’s see how to use SQLite in Xamarin.Forms

First let’s talk about few things that we should know while implementing SQLite.

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 platform-specific SQLite connection that is required in this implementation.

  • Shared Projects: Shared Projects can directly incorporate the Net source from GitHub and reference those SQLite classes. Compiler directives are used when platform-specific code is required (such as determining the location of the SQLite data file).

Most SQLite.NET code is shareable across all the platforms; only configuring the database connection and location of the SQLite database file requires platform-specific functionality. This is explained below for each solution type.

In this post I will use SQLite with Xamarin.Forms PCL template.

Create new project and add SQLite support

Let’s create new project and I named it “XamarinSqliteSample”.

XamarinSqliteSample

Now we need to install a new package into our project named SQLite.Net. This is a .NET wrapper around SQLite that will allow us to access the native SQLite functionality from a Xamarin.Forms PCL or shared project. To add SQLite support to a Xamarin.Forms PCL template solution, start with the shared PCL library. Right-click and choose Manage NuGet Packages to add SQLite.Net support.

Search SQLite.Net PCL and install the package as in the following screenshot:

SQLite

Once the reference has been added, write an Interface to abstract any platform-specific functionality. For SQLite.Net the only platform-specific work required is to determine the location of the database file and create a connection. Within your PCL project, create a new interface named ISQLite and replace the definition with the following:

  1. using SQLite.Net;  
  2. namespace XamarinSqliteSample  
  3. {  
  4.    public interface ISQLite  
  5.    {  
  6.       SQLiteConnection GetConnection();  
  7.    }  
  8. }  
This is the interface that we will implement and get access connection via DependencyService from the native projects.

Let’s create a Database

We now have access to the SQLite functionality and let’s define our database. In this simple application we are just keeping student records. Let’s call this class Student.
  1. using System;  
  2. using SQLite.Net.Attributes;  
  3.    
  4. namespace XamarinSqliteSample  
  5. {  
  6.     public class Student  
  7.     {  
  8.         [PrimaryKey, AutoIncrement]  
  9.         public int Id { getset; }  
  10.         public string Name { getset; }  
  11.         public string Address { getset; }  
  12.         public string Phone { getset; }  
  13.    
  14.         public Student()  
  15.         {  
  16.         }  
  17.     }  
  18. }  
As you see above we got four columns where Id is set as PrimaryKey and AutoIncrement.

Now for simplicity let’s create a class that represents my database and keep all the logic to access the database and its tables within this class. I will call it StudentDB.
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using SQLite.Net;  
  4. using Xamarin.Forms;  
  5.    
  6. namespace XamarinSqliteSample  
  7. {  
  8.     public class StudentDB  
  9.     {  
  10.         private SQLiteConnection _sqlconnection;  
  11.    
  12.         public StudentDB()  
  13.         {  
  14.             //Getting conection and Creating table  
  15.             _sqlconnection = DependencyService.Get<ISQLite>().GetConnection();  
  16.             _sqlconnection.CreateTable<Student>();  
  17.         }  
  18.    
  19.         //Get all students  
  20.         public IEnumerable<Student> GetStudents()  
  21.         {  
  22.             return (from t in _sqlconnection.Table<Student>() select t).ToList();  
  23.         }  
  24.    
  25.         //Get specific student  
  26.         public Student GetStudent(int id)  
  27.         {  
  28.             return _sqlconnection.Table<Student>().FirstOrDefault(t => t.Id == id);  
  29.         }  
  30.    
  31.         //Delete specific student  
  32.         public void DeleteStudent(int id)  
  33.         {  
  34.             _sqlconnection.Delete<Student>(id);  
  35.         }  
  36.    
  37.         //Add new student to DB  
  38.         public void AddStusent(Student student)  
  39.         {  
  40.             _sqlconnection.Insert(student);  
  41.         }  
  42.     }  
  43. }  
In StudentDB() constructor we are doing two things. Firstly, we are using the DependencyService class to get a registered class that implements the ISQLite interface and call it GetConnection method.

Secondly, we use the CreateTable method on the SQLiteConnection class to create a table called Student. This method will create the table, if it doesn’t already exist, and exit if it already exists.

iOS implementation

The main obstacle that we need to work around on the native side when using SQLite is where we are going to store the actual database file. This differs from platform to platform.

Before we can actually add any sort of SQLite functionality to the iOS project, we need to add the SQLite.Net PCL as well as the SQLite.NET PCL – XamarinIOS Platform packages to this project from Nuget as earlier. Once you have added these packages, you can start to write some SQLite code within the iOS project.

Let’s create class SQLite_iOS class and implement ISQLite interface.
  1. using System;  
  2. using Xamarin.Forms;  
  3. using XamarinSqliteSample.iOS;  
  4. using System.IO;  
  5.    
  6. [assembly:Dependency(typeof(SQLite_iOS))]  
  7. namespace XamarinSqliteSample.iOS  
  8. {  
  9.     public class SQLite_iOS: ISQLite  
  10.     {  
  11.         public SQLite.Net.SQLiteConnection GetConnection ()  
  12.         {  
  13.             var fileName = "Student.db3";  
  14.             var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);  
  15.             var libraryPath = Path.Combine (documentsPath, "..""Library");  
  16.             var path = Path.Combine (libraryPath, fileName);  
  17.    
  18.             var platform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS ();  
  19.             var connection = new SQLite.Net.SQLiteConnection (platform, path);  
  20.    
  21.             return connection;  
  22.         }  
  23.     }  
  24. }  
The assembly attribute at the top of the file is used to identify this class as a Dependency that can be retrieved via the Get method on the DependencyService class. Now we get access to the correct location to store the database file, create a new SQLiteConnection object, and pass it back to our PCL project.

Android implementation

Android implementation is also very similar to the iOS implementation only, the difference will be that the location of the database file will be different. Here also you need to add packages (SQLite.Net PCL and SQLite.NET PCL – XamarinAndroid) from Nuget. Now let’s create SQLite_Android class and implement ISQLite interface.
  1. using System;  
  2. using System.IO;  
  3. using Xamarin.Forms;  
  4. using XamarinSqliteSample.Droid;  
  5.    
  6. [assembly: Dependency(typeof(SQLite_Android))]  
  7. namespace XamarinSqliteSample.Droid  
  8. {  
  9.     public class SQLite_Android: ISQLite  
  10.     {  
  11.         public SQLite.Net.SQLiteConnection GetConnection()  
  12.         {  
  13.             var filename = "Student.db3";  
  14.             var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);  
  15.             var path = Path.Combine(documentspath, filename);  
  16.    
  17.             var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();  
  18.             var connection = new SQLite.Net.SQLiteConnection(platform, path);  
  19.             return connection;  
  20.         }  
  21.     }  
  22. }  
You now have a working implementation of the ISQLite interface for your android app.

Windows Phone Implementation

For Windows phone you should have to do a little more work. The SQLite database engine is built-in to the iOS and Android operating systems. To add SQLite support to Windows Phone projects follow this instruction.

After installing SQLite, lets add the packages from Nuget to our project SQLite.NetPCL and SQLite.Net PCL – WindowsPhone 8 Platform. With these packages installed, you can create the Windows Phone implementation of the ISQLite interface.
  1. using Xamarin.Forms;  
  2. using XamarinSqliteSample.WinPhone;  
  3. using System.IO;  
  4. using Windows.Storage;  
  5.    
  6. [assembly: Dependency(typeof(SQLite_WinPhone))]  
  7. namespace XamarinSqliteSample.WinPhone  
  8. {  
  9.     public class SQLite_WinPhone: ISQLite  
  10.     {  
  11.         public SQLite_WinPhone()  
  12.         {  
  13.         }  
  14.         public SQLite.Net.SQLiteConnection GetConnection()  
  15.         {  
  16.                 var filename = "Student.db3";  
  17.                 var path = Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);  
  18.    
  19.                 var platfrom = new SQLite.Net.Platform.WindowsPhone8.SQLitePlatformWP8();  
  20.                 var connection = new SQLite.Net.SQLiteConnection(platfrom, path);  
  21.                 return connection;     
  22.         }  
  23.     }  
  24. }  
Ok, that’s it for the SQLite implementation part. Now it’s time for creating UI.

Adding User Interface

For this sample application I will make our interface simple. I have created two pages wherein first page (Register.Xaml) user can register student details and in second page (StudentList.Xaml) the list of added students is displayed.

Here is the code view of Register.xaml and Register.xaml.cs.

code view of Register

Register

And here is the code view of StudentList.xaml and StudentList.xaml.cs.

code

StudentList

In my case I run this app in Windows Phone and it works fine. Here are the screenshots:

run this app

Windows Phone

That’s it. Now you can add database functionality on your Xamarin.Forms app.

You can download complete code from here.

Happy Coding.

 


Similar Articles