Interacting With Local Database in Xamarin.Forms

Introduction

It's very common for a mobile application to use a local SQLite database. The combination of Sqlite.net and Xamarin.Forms makes this very easy. One of the reasons that we choose SQLite as our mobile database is that it's a single file and easily works across platforms. iOS and Android both have the SQLite database engine "built in” and access to the data is simplified by Xamarin's platform that comes with the SQLite Data Provider.

Here I'm showing how to create a small project to store my notes into the local database. In this app we can save data, view the saved data and also we can update and delete the saved data.

Before beginning to use it we must add the "SQLite.Net-PCL" NuGet package to the solution.

 

Figure 1: Add SQLite Net PCL NuGet package

There is one more important task to do before coding, that is to add a SQLite reference for Windows Phone 8.0. For that right-click on References in the Windows Phone project and select "Add references".

 

Figure 2: Add References

Now we can create a model in our shared project named "NotesDB.cs".

 

Figure 3: Create a model in our shared project

Here we want to use dependency services to define the path or location for our database to be saved and for the SQLite connection. For that I have created an interface "INotes.cs".

 

Figure 4: Interface INotes

Now we can implement each platform so that we can determine the data file path and create a new connection.

iOS Implementation

 

Figure 5: iOS Implementation

Android Implementation

 

Figure 6: Android Implementation

Windows Phone Implementation

 

Figure 7: Windows Phone Implementation

Now let's add a bit of code for the manipulation of the database by creating a class "NotesQuery.cs". The code for the manipulations is given below.

Getting connection and creating table

 

Figure 8: Getting connection and creating table

Insert data

 

Figure 9: Insert Data

Update data

 

Figure 10: Update Data

Delete Data

 

Figure 11: Delete Data

See more info with the sample attached to this article.


Similar Articles