I'm trying to make SQLite work to store some information locally and by now I've encountered an annoying issue: whenever I call the sqlite function CreateTable it gives me back an exception.
Here's the exception:
Unhandled Exception:
System.MissingMethodException: Method not found: string SQLitePCL.raw.sqlite3_column_name(SQLitePCL.sqlite3_stmt,int).
Here's the Interface I used to make it cross-platform:
public interface IDataBase
{
SQLiteConnection GetConnection();
}
The Android implementation:
[assembly: Dependency(typeof(DataBase))]
namespace MyNameSpace.Droid
{
public class DataBase : IDataBase
{
public DataBase() { }
public SQLiteConnection GetConnection()
{
var fileName = "DataBase.db3";
string docsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string path = Path.Combine(docsPath, fileName);
var conn = new SQLiteConnection(path);
return conn;
}
}
}
And the one for iOs:
[assembly: Dependency(typeof(DataBase))]
namespace MyNameSpace.iOS
{
public class DataBase : IDataBase
{
public DataBase() { }
public SQLiteConnection GetConnection()
{
var fileName = "DataBase.db3";
var docPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var libraryPath = Path.Combine(docPath, "..", "Library");
var path = Path.Combine(libraryPath, fileName);
var conn = new SQLiteConnection(path);
return conn;
}
}
}
Then I have my Table type:
namespace MyNameSpace.DataBase
{
public class MacroCategoria
{
[PrimaryKey]
public int ID { get; set; }
public string descrizione { get; set; }
public MacroCategoria() { }
}
}
The DataBase controller and I method that gets the first element:
namespace MyNameSpace.DataBase
{
public class DBController
{
static object locker = new object();
SQLiteConnection database;
public DBController()
{
database = DependencyService.Get<IDataBase>().GetConnection();
if (database != null)
{
database.CreateTable<MacroCategoria>();
database.Insert(new MacroCategoria() { ID = 0, descrizione = "Description" });
}
}
public MacroCategoria getFirstMacro()
{
lock (locker)
{
if (database.Table<MacroCategoria>().Count() == 0)
return null;
else
return database.Table<MacroCategoria>().First();
}
}
}
}
Which is called in the App class:
public partial class App : Application
{
static DBController dbController;
public App()
{
InitializeComponent();
DependencyService.Register<MockDataStore>();
MainPage = new MainPage();
}
[...Other Default Methods...]
public static DBController DBController
{
get
{
if(dbController == null)
{
dbController = new DBController();
}
return dbController;
}
}
}
And finally, when in my mainPage i have a function that's supposed to get the first element:
private void CartIcon_Clicked(object sender, EventArgs e)
{
try
{
App.DBController.getFirstMacro();
} catch(Exception ex) { throw; }
}