Skip to content

Instantly share code, notes, and snippets.

@adamped
Created January 8, 2016 02:14
Show Gist options
  • Save adamped/677e8198c073d93f8a2e to your computer and use it in GitHub Desktop.
Save adamped/677e8198c073d93f8a2e to your computer and use it in GitHub Desktop.
SQLite for Android
public class SQLite_Android : ISQLite
{
private SQLiteConnectionWithLock _conn;
public SQLite_Android()
{
}
private string GetDatabasePath()
{
var sqliteFilename = "DatabaseName.db3";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, sqliteFilename);
return path;
}
public SQLiteAsyncConnection GetAsyncConnection()
{
var dbpath = GetDatabasePath();
var platForm = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
var connectionFactory = new Func<SQLiteConnectionWithLock>(
() =>
{
if (_conn == null)
{
_conn =
new SQLiteConnectionWithLock(platForm,
new SQLiteConnectionString(dbpath, storeDateTimeAsTicks: false));
}
return _conn;
});
return new SQLiteAsyncConnection(connectionFactory);
}
public void DeleteDatabase()
{
var path = GetDatabasePath();
try
{
if (_conn != null)
{
_conn.Close();
}
}
catch (Exception ex)
{
// Best effort close. No need to worry if throws an exception
}
if (File.Exists(path))
{
File.Delete(path);
}
_conn = null;
}
public void CloseConnection()
{
if (_conn != null)
{
_conn.Close();
_conn.Dispose();
_conn = null;
// Must be called as the disposal of the connection is not released until the GC runs.
GC.Collect();
GC.WaitForPendingFinalizers();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment