0

According to the tutorial I found, I declared the path for android to the db3 file in the MainActivity.cs like this:

        string fileName = "galleries.db3";
        string folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        string completePath = Path.Combine(folderPath, fileName);

        LoadApplication(new App(completePath));

and in the App.xaml.cs I added this:

    public App(string filePath)
    {
        InitializeComponent();

        MainPage = new NavigationPage(new GalleryList());
        FilePath = filePath;
    }

I would like to access this path inside a class, like this:

    using (SQLiteConnection conn = new SQLiteConnection(App.FilePath))

But get the error message that I have to specify a Path, and the variable is Null. How can I make this path available inside a class?

sharkyenergy
  • 3,842
  • 10
  • 46
  • 97
  • "tutorial I found" - have you considered following the official docs? https://learn.microsoft.com/en-us/xamarin/get-started/quickstarts/database?pivots=windows – Jason Mar 18 '20 at 21:07
  • thanks, having a look at it. – sharkyenergy Mar 18 '20 at 21:10
  • I've checked it out, but still cannot figure out how to pass the path to my class. If I do it like in the link, then I will have to pass the database instance to my class somehow, and would be at the same point.. right? – sharkyenergy Mar 18 '20 at 21:40
  • You can just do it in the shared code when you create the db. You don't need to pass it in from the platform project. – Jason Mar 18 '20 at 21:46
  • Sorry, i am just begining with all this, not sure i follow you. What I am trying to do: I have a CollectionView, and a "service" class that gets all the data and passes them to the ViewModel. In this service class i am trying to connect to the database in order to read all the needed data, but I am unable to tell the path to the database. I tried with the code from the sample but it gives problems due to the public function. – sharkyenergy Mar 18 '20 at 21:50
  • in your specific case it might be as simple as setting `FilePath = filePath;` **before** you set `MainPage` – Jason Mar 18 '20 at 21:53
  • Run or i kiss you.. :D thank you soo much! That fixed it. Could you please post it as answer so I can accept it? – sharkyenergy Mar 18 '20 at 21:55

1 Answers1

1

you are executing your db code (in GalleryList) before you assign FilePath

MainPage = new NavigationPage(new GalleryList());
FilePath = filePath;

instead, assign FilePath first

FilePath = filePath;
MainPage = new NavigationPage(new GalleryList());
Jason
  • 86,222
  • 15
  • 131
  • 146