Data Persistence Using SQLite In Xamarin.Forms

Introduction

In this article, we are going to make our data persistence using SQLite in Xamarin.Forms. Firstly, we will setup SQLite db for our project, then make a table in it, and add some data in this table. After this, whenever we open our application, we will see that our data is now persisted and saved in local db of application.

Setup SQLite for your project

See this article to setup SQLite in your project or follow the steps blow:

Three steps are needed to setup SQLite db.

  • Install sqlite-net-pcl into your solution from NuGet Package.
  • Declare Interface in PCL project.
  • Implement this interface in all three projects.

Firstly, install sqlite-net-pcl, then declare and implement interface. Details are given below.

Declaring Interface

  1. using SQLite;  
  2.   
  3. namespace XamarinApp1.Persistence  
  4. {  
  5.     public interface ISQLiteDb  
  6.     {  
  7.         SQLiteAsyncConnection GetConnection();  
  8.     }  
  9. }  
*Change namespace according to your project name.

Declare this interface in PCL.

Implement interface

Now, implement this interface in all three projects. By implementing this interface, you can set database path of each application. For Android and iOS code, it remains same but for Windows, it is slightly different.

For Android and iOS.

  1. using System;  
  2. using SQLite;  
  3. using XamarinApp1.Persistence;  
  4. using System.IO;  
  5. using Xamarin.Forms;  
  6. using XamarinApp1.iOS.Persistence;  
  7.   
  8. [assembly: Dependency(typeof(SQLiteDb))]  
  9.   
  10. namespace XamarinApp1.iOS.Persistence  
  11. {  
  12.     public class SQLiteDb : ISQLiteDb  
  13.     {  
  14.         public SQLiteAsyncConnection GetConnection()  
  15.         {  
  16.             var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);  
  17.             var path = Path.Combine(documentsPath, "MySQLite.db3");  
  18.   
  19.             return new SQLiteAsyncConnection(path);  
  20.         }  
  21.     }  
  22. }  

For Windows

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Threading.Tasks;  
  6. using SQLite;  
  7. using XamarinApp1.Persistence;  
  8. using Windows.Storage;  
  9. using System.IO;  
  10. using Xamarin.Forms;  
  11.   
  12. [assembly: Dependency(typeof(XamarinApp1.UWP.Persistence.SQLiteDb))]  
  13.   
  14. namespace XamarinApp1.UWP.Persistence  
  15. {  
  16.     public class SQLiteDb : ISQLiteDb  
  17.     {  
  18.         public SQLiteAsyncConnection GetConnection()  
  19.         {  
  20.               
  21.             string documentPath = ApplicationData.Current.LocalFolder.Path;  
  22.             string path = Path.Combine(documentPath, "MySQLite.db3");  
  23.   
  24.             return new SQLiteAsyncConnection(path);  
  25.         }  
  26.     }  
  27. }  

Save a data in SQLite (Make your application data persistent)

In this example, we will make a simple textbox. Anything you write and submit through this textbox is saved in your db. First, make a test class in PCL project through which our db table is generated.

Here is our test class code.

  1. public class test  
  2.  {  
  3.      [PrimaryKey, AutoIncrement]  
  4.      public int id { get; set; }  
  5.   
  6.      [MaxLength(255)]  
  7.      public string Title { get; set; }  
  8.   
  9.      [MaxLength(1000)]  
  10.      public string Desc { get; set; }  
  11.  }  

Now, write XAML code for it and make a user interface to save data.

XAML

  1. <StackLayout>  
  2.     <Label Text="Save Your Notes:"></Label>  
  3.     <Entry Placeholder="Enter Notes Title" x:Name="Title"></Entry>  
  4.     <Entry Placeholder="Enter Notes Description" x:Name="Description"></Entry>  
  5.     <Button Text="ADD NOTE" Clicked="OnAdd"></Button>  
  6.   
  7.     <Label Text="Saved Note" VerticalOptions="End"></Label>  
  8.     <ListView VerticalOptions="EndAndExpand" x:Name="mylistview">  
  9.         <ListView.ItemTemplate>  
  10.             <DataTemplate>  
  11.                 <TextCell Text="{Binding Title}" Detail="{Binding Desc}"></TextCell>  
  12.             </DataTemplate>  
  13.         </ListView.ItemTemplate>  
  14.     </ListView>  
  15. </StackLayout>  

Output

Output

Code

  1. public partial class SQLiteDbTest : ContentPage  
  2.     {  
  3.         private SQLiteAsyncConnection _connection;  
  4.         private ObservableCollection<test> _test;  
  5.   
  6.         public SQLiteDbTest()  
  7.         {  
  8.             InitializeComponent();  
  9.             _connection = DependencyService.Get<ISQLiteDb>().GetConnection();  
  10.   
  11.         }  
  12.   
  13.         protected async override void OnAppearing()  
  14.         {  
  15.            await _connection.CreateTableAsync<test>();  
  16.             var abc = await _connection.Table<test>().ToListAsync();  
  17.             _test = new ObservableCollection<test>(abc);  
  18.             mylistview.ItemsSource = _test;  
  19.   
  20.             base.OnAppearing();  
  21.         }  
  22.   
  23.         void OnAdd(object sender, System.EventArgs e)  
  24.   
  25.         {  
  26.             var test = new test { Title = Title.Text, Desc = Description.Text };  
  27.             _connection.InsertAsync(test);  
  28.             _test.Add(test);  
  29.         }  
  30.     }  
  31. }  

Now, add some data and see the result.

Output

By clicking on Add Note Button,

Output

Your first note is saved in db of application. Now, this data is persistent and no matter how many times you close your application or open it, your data remains here.


Similar Articles