![]() |
1. Storing Data
So why do you need to care about data when it comes to your app? Because it is all around you. You can't escape it. No matter what kind of app you are writing, whether it's a game or some sort of utility, you are going to need to store data at some point. That data could be user data, statistics, or anything else of interest that either you or the user will be interested in at some point in the use of your app.
At this point, let's assume that you have decided to go the Xamarin.Forms route, because you are interested in targeting several platforms not only in the logic for your app, but also for the user interface layer.
Great. But what do you do now that you need to store information within your app? Don't worry, there's a very simple solution to this problem, SQLite.
2. Introduction to SQLite
You have now seen the term SQLite a couple of times in this tutorial, it's time to get down to the meat. What exactly is SQLite? SQLite is a public domain, zero configuration, transactional SQL database engine. All this means is that you have a full featured mechanism to store your data in a structured way. Not only do you get all of this, you also have access to the source code, because it's open source.
We will not be covering all the features of SQLite in this tutorial simply because there are too many to go through. Rest assured that you will have the ability to easily create a table structure to store data and retrieve it in your app. These are the concepts that we will be focusing on in this tutorial.
In the world of Xamarin.Forms, SQLite is a natural fit for a very simple reason. The SQLite engine is readily available on both iOS and Android. This means that you can use this technology right out of the box when you choose to write a Xamarin.Forms app.
Getting access to SQLite functionality in Windows Phone apps requires one additional step that we will go over a little later. All this functionality and cross platform accessibility is great, but how will we get access to the native platform implementations from our C# code in Xamarin.Forms? From a nice NuGet package, that's how. Let's take a look.
3. Creating an App
Let's start by creating a simple Xamarin.Forms application. In this tutorial, I will be using a Mac running Xamarin Studio, but you can just as easily be using Xamarin Studio or Visual Studio running on a PC.
Step 1: Create a Project
We start the process by creating a new Xamarin.Forms app. To do this, simply select the Mobile Apps project template family on the left and choose one of the Xamarin.Forms templates on the right. You can use either the PCL or Shared version of the template, but for this case, I will be using the PCL. You can follow along using either one, but there will be a slight difference if you choose the Shared template later on.
![]() |
- IntroToSQLite - PCL project
- IntroToSQLite.Android - Android project
- IntroToSQLite.iOS - iOS project
- IntroToSQLite.WinPhone - Windows Phone project (only on a PC)
Now that we have our basic project structure set up, we can start to add access to SQLite to our PCL project. 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.
We access this NuGet package by right-clicking on either Packages or References, depending on which IDE you are using, and select Add Package (or Reference). In the search box, type sqlite.net. This will show you a rather large collection of packages that you can include in your project.
![]() |
SQLite and Shared Projects
If you've chosen the Shared project template earlier in the tutorial, you may be wondering how to get access to the SQLite package. The short answer is that you can't. If you remember from a previous tutorial, you can't add references to a Shared project. To get access to SQLite from a Shared project, you simply add the source code to the project.
Add Some Code
The final step in adding SQLite functionality to the PCL project is to create an interface that will allow us access into the SQLite world. The reason we are doing this is because we need to access the native functionality on the different platforms as we saw in a previous tutorial.
Let's start by defining an interface that is going to give us access to the SQLite database connection. Within your PCL project, create a new interface named ISQLite and replace the implementation with the following:
- using System;
- using SQLite.Net;
- namespace IntroToSQLite
- {
- public interface ISQLite
- {
- SQLiteConnection GetConnection();
- }
- }
Step 3: Define the Database
We now have access to the SQLite functionality, let's define our database. This particular application is going to be quite simple and we are just going to store some of our random thoughts as we come up with them.
We start by creating a class that will represent the data stored in a particular table. Let's call this class RandomThought.
- using System;
- using SQLite.Net.Attributes;
- namespace IntroToSQLite
- {
- public class RandomThought
- {
- [PrimaryKey, AutoIncrement]
- public int ID { get; set; }
- public string Thought { get; set; }
- public DateTime CreatedOn { get; set; }
- public RandomThought ()
- {
- }
- }
- }
The interesting thing about the ID property is that it is decorated with two attributes, PrimaryKey and AutoIncrement. PrimaryKey tells SQLite that this column is going to be the primary key of the table, which means that, by default, it needs to be unique and there is an index applied to it to speed up retrievals from this table when referring to a row by this column.
AutoIncrement means that, when we insert a new RandomThought into this table, the ID column will be populated automatically with the next available integer value. The next step is to create this table in the database.
I like to create a class that represents my database and keep all the logic to access the database and its tables within this class. For this, I will create a class named RandomThoughtDatabase:
- using System;
- using SQLite.Net;
- using Xamarin.Forms;
- using System.Collections.Generic;
- using System.Linq;
- namespace IntroToSQLite
- {
- public class RandomThoughtDatabase
- {
- private SQLiteConnection _connection;
- public RandomThoughtDatabase ()
- {
- _connection = DependencyService.Get<ISQLite> ().GetConnection ();
- _connection.CreateTable<RandomThought> ();
- }
- public IEnumerable<RandomThought> GetThoughts() {
- return (from t in _connection.Table<RandomThought> ()
- select t).ToList ();
- }
- public RandomThought GetThought(int id) {
- return _connection.Table<RandomThought> ().FirstOrDefault (t => t.ID == id);
- }
- public void DeleteThought(int id) {
- _connection.Delete<RandomThought> (id);
- }
- public void AddThought(string thought) {
- var newThought = new RandomThought {
- Thought = thought,
- CreatedOn = DateTime.Now
- };
- _connection.Insert (newThought);
- }
- }
- }
First, we are using the DependencyService class to get a registered class that implements the ISQLite interface and call its GetConnection method.
Second, we use the CreateTable method on the SQLiteConnection class to create a table called RandomThought. This method will create the table, if it doesn't already exist, and exit gracefully if it already exists.
Obviously, you can get as sophisticated with this class as you want by adding all sorts of functionality, but these operations are typically a good starting point.
Step 4: Add the iOS Implementation
Most of the code that we use to interact with the database is going to be found in the PCL (or Shared) project. But we still need to do a little wiring up in the native implementations to get everything working correctly.
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. Here is what we need for iOS.
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. You can follow the same steps that you took in Step 2, making sure to add both to the project. Once you have added this package, you can start to write some SQLite code within the iOS project.
Let's create an implementation of the ISQLite interface for iOS. Start by creating a new class, naming it SQLite_iOS.
- using System;
- using System.IO;
- using SQLite;
- using IntroToSQLite.iOS;
- using Xamarin.Forms;
- [assembly: Dependency(typeof(SQLite_iOS))]
- namespace IntroToSQLite.iOS
- {
- public class SQLite_iOS: ISQLite
- {
- public SQLite_iOS ()
- {
- }
- #region ISQLite implementation
- public SQLite.Net.SQLiteConnection GetConnection ()
- {
- var fileName = "RandomThought.db3";
- var documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
- var libraryPath = Path.Combine (documentsPath, "..", "Library");
- var path = Path.Combine (libraryPath, fileName);
- var platform = new SQLite.Net.Platform.XamarinIOS.SQLitePlatformIOS ();
- var connection = new SQLite.Net.SQLiteConnection (platform, path);
- return connection;
- }
- #endregion
- }
- }
If you found this post interesting, follow and support us.
Suggest for you:
Ionic 2 Tutorial with Two Complete Apps
Android Application Programming - Build 20+ Android Apps
The Complete Android Developer Course - Build 14 Apps
The Complete Android & Java Course - Build 21 Android Apps
Android: From Beginner to Paid Professional
No comments:
Post a Comment