N. Smeding N. Smeding - 1 month ago 5
Android Question

How can i let my code make a sqlite database when it doens't exist?

I am trying to make a sqlite database but I can't succeed. the big problem with this is that I don't get any error. I can't even make a .db file manually because it will not be found. I am working with Xamarin forms and I use visual studio 2015 to edit my code/files. This is my code:

ISQLite interface:

...
public interface ISQLite
{
SQLiteConnection GetConnection();
}
...


DB helper (called TheMapDB.cs):

...
public class TheMapDB
{
private SQLiteConnection db;

public TheMapDB()
{
//Getting conection and Creating table
db = DependencyService.Get<ISQLite>().GetConnection();
db.CreateTable<Categories>();
db.CreateTable<Places>();
db.CreateTable<Events>();
}

public void AddCategorie(Categories categorie)
{
db.Insert(categorie);
}
}
...


Tables (file called Tables.cs):

public class Categories
{
[PrimaryKey, AutoIncrement]
public int ID { get; set; }
public int Menu_ID { get; set; }
public string Name { get; set; }

public Categories()
{
}
}


android native side(called SQLite_Android.cs):

[assembly: Dependency(typeof(SQLite_Android))]
namespace AmsterdamTheMapV3.Droid
{
public class SQLite_Android : ISQLite
{
public SQLite_Android() { }
public SQLite.Net.SQLiteConnection GetConnection()
{
var filename = "database.db3";
var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(documentspath, filename);

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


how I call the functions:

static TheMapDB database;
Categories student = new Categories();
TheMapDB categorie = new TheMapDB();

public HomePage()
{
student.ID = 1;
student.Menu_ID = 2;
student.Name = "peter";
categorie.AddCategorie(student);
NavigationPage.SetHasNavigationBar(this, false);
categorie.GetCategorie(1);
InitializeComponent();
}


I know that it is a lot of code but i have no idea where the problem is.
I can give more info if needed.
Thank you in advance.

Answer

Please replace :-

 var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

With

 var documentspath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

It might be a issue of folder access .

Edited :-

Also before creating database, please also put a condition to check if it already created, otherwise it will replace the database.

Comments