tatoes
tatoes

Reputation: 19

Using SQLite database in Xamarin.Forms

I have created a SQLite database (using the cmd shell sqlite3.exe) and am now trying to implement it within Xamarin.Forms using this page https://developer.xamarin.com/guides/android/application_fundamentals/data/part_3_using_sqlite_orm/ as guidance. I'm confused, though, because I have no idea what the path to the database is. I named the database "app" and the table "tbl1" but that's all the information about it that I know. The database simply stores usernames and passwords, and is used on the login page of my cross-platform app only.

Upvotes: 0

Views: 811

Answers (1)

TaiT's
TaiT's

Reputation: 3216

Using Xamarin.Forms (your link is for Android!), you will have to use some kind of abstraction from your shared project in order to access your database (which is platform specific). This is how you can basically get the right storage path per platform.

This means basically to create an Interface in the shared project, i.e:

public interface IFileHelper
{
  string GetLocalFilePath(string filename);
}

Then, you must implement the platform specific parts. I.e Android:

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.Droid
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            return Path.Combine(path, filename);
        }
    }
}

iOS:

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.iOS
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            string docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            string libFolder = Path.Combine(docFolder, "..", "Library", "Databases");

            if (!Directory.Exists(libFolder))
            {
                Directory.CreateDirectory(libFolder);
            }

            return Path.Combine(libFolder, filename);
        }
    }
}

UWP:

using Windows.Storage;
...

[assembly: Dependency(typeof(FileHelper))]
namespace Todo.UWP
{
    public class FileHelper : IFileHelper
    {
        public string GetLocalFilePath(string filename)
        {
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        }
    }
}

Then to retrieve and use The most simple approach is to use Xamarin's DependencyService. More info here.

Here is the official documentation about local databases.

Hope it helps!

Upvotes: 1

Related Questions