Search code examples
xamarin.androidsqlite-net

sqlite-net fails to create database in MonoDroid application


I start Xamarin Studio 4.0.3 and create a new solution for MonoDroid application. I am targetting version 2.3 or higher. I include Sqlite.cs from the sqlite-net (latest from site) project. I make sure I have a reference to Mono.Data.SQLite in the project. Then in the OnCreate of the default MainActivity I try to use the code shown in the readme to make a database connection:

string path = Android.OS.Environment.DataDirectory.ToString();

string dbname = path + "/" + "test.db3";
var db = new SQLiteConnection(dbname, SQLiteOpenFlags.Create|SQLiteOpenFlags.ReadWrite ,true);

However it always fails with an exception saying it can't open the database. If I follow Greg Shackles example and use SqliteDbHelper method it works, but I would like to understand what I am doing wrong that sqlite-net connection method is not working. I have a feeling I am missing something simple. I did also try just passing in a filename to SQLiteConnection() as well but when it failed I added the OpenFlags to see if that was the issue.


Solution

  • I just found out that apparently you're supposed to use the personal folder, instead of the databases folder:

    string folder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
    var db = new SQLiteConnection(Path.Combine(folder, "mydb.db"));