Adding a SQLite Database to Android

Implementing a SQLite database on Android went a bit quicker after the iOS work. The steps involved were:

  1. Adding the SQLite.Net NuGet package to the Android project
  2. Creating an ItemSQLite.db3 link in the Android project
  3. Coding the SQLite_Android iSQLite interface implementation

Adding the SQLite.Net NuGet package was done the same way as iOS–select the Packages folder in the Viand.Droid project, right click, and select Add Packages.

NuGet-Add-Packages-SQLite.Net

I added a link to theItemSQLite.db3 database to the Assets folder in the Viand.Droid project, set it’s Build action to AndroidAsset and flagged it as Do Not Copy to the Output directory.

Coding the corresponding SQLite_Android implementation of the ISQLite interface was relatively straightforward with

[assembly: Dependency(typeof(SQLite_Android))]

namespace Viand.Droid
{
	public class SQLite_Android : ISQLite
	{
		const string sqliteFilename = "ItemSQLite.db3";

		public SQLite_Android() {}

		public SQLiteConnection GetConnection()
		{
			string documentsPath;
			string databasePath;

			documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
			databasePath = Path.Combine(documentsPath, sqliteFilename);

			CopyDatabaseIfNotExist(databasePath);

			var platform = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
			var connection = new SQLite.Net.SQLiteConnection(platform, databasePath);

			return connection;
		}

		private static void CopyDatabaseIfNotExist(string databasePath)
		{
			if (!File.Exists(databasePath)) {
				using (var br = new BinaryReader(Android.App.Application.Context.Assets.Open(sqliteFilename))) {
					using (var bw = new BinaryWriter(new FileStream(databasePath, FileMode.Create))) {
						byte[] buffer = new byte[2048];
						int length = 0;
						while ((length = br.Read(buffer, 0, buffer.Length)) > 0) {
							bw.Write(buffer, 0, length);
						}
					}
				}
			}
		}
	}
}

Some links that were helpful during development.

This entry was posted in Side Projects, Software Development and tagged , , , , . Bookmark the permalink.