I'm writing a simple Xamarin Forms mobile app (Android and iOS, but focusing on Android for now) as a school project. I'm using Visual Studio 2019 Community and I have installed the NuGet package sqlite-net-pcl v1.7.335
Everything was moving along when suddenly the application started throwing errors any time database access was attempted, saying "DatabasePath must be specified".
Concerned I might have made an error in my code, I created a blank application and attempted only a simple database connection. The same error occurs. Please see my code below.
MainActivity.cs
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
{
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
string fileName = "datahold.db";
string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
string completePath = Path.Combine(folderPath, fileName);
LoadApplication(new App(completePath));
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
App.xaml.cs
public App(string filePath)
{
InitializeComponent();
MainPage = new MainPage();
dbPath = filePath;
}
MainPage.xaml.cs
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
using (SQLiteConnection myCon = new SQLiteConnection(App.dbPath))
{
myCon.CreateTable<term>();
}
}
}
Upon attempting to run the program, it highlights the using line above and gives:
System.InvalidOperationException Message=DatabasePath must be specified
I can correct this issue only by moving the definition of the database into MainPage itself. From there the rest of my program seems to be able to access that database file by referencing MainPage.dbPath; however, the lack of communication between App.xaml and MainPage.xaml is very concerning and is likely to have further ramifications I am too inexperienced to predict. Is this something I can fix with some sort of patch? Should I change out sqlite-net-pcl for something else?
you are creating
MainPage
before you assigndbPath
, so when theMainPage
constructor executesdbPath
isnull
assign
dbPath
first