0

EDIT : I will leave this here with the full instructions to my solution to add a premade database to xamarin forms in case any one ever needs it.

So I have a Database (.db3 / .db File) and I use "DB Browser for SQLite" (https://sqlitebrowser.org/) to create and view my database.

**IMPORTANT : The class name in the next part must be EXACTLY the same as the table name. So if the table is named "Items" your class must also be named "Items"


Targeting IOS / Android / UWP

So here are my steps as to what I'm doing, maybe someone can tell me what I'm doing wrong.

  • Open visual studios > Xamarin Forms > Blank App
  • Install NuGet package sqlite-net-pcl to my project
  • Create a class to handle my Items like so
public class Item
{

    [PrimaryKey, AutoIncrement]
    public int Id { get; set; }
    public int Name { get; set; }
    public int Category { get; set; }
}
  • Add a ListView to my MainPage.xaml like so, called itemListView
        <Grid>
            <ListView x:Name="itemListView">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <TextCell Text="{Binding Name}"
                                  Detail="{Binding Category}"/>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>
        </Grid>
  • I change MainPage.xaml.cs to the following code
    public MainPage()
    {
        InitializeComponent();
    }

    protected override void OnAppearing()
    {
        base.OnAppearing();

        using (SQLiteConnection conn = new SQLiteConnection(App.DatabasePath))
        {
            conn.CreateTable<Item>();
            var items = conn.Table<Item>().ToList();

            itemListView.ItemsSource = items;
        }
    }
  • Next, I change my App.xaml.cs , adding a DatabasePath string and changing the App constructor method to the following
    public static string DatabasePath = string.Empty;

    public App(string databasePath)
    {
        InitializeComponent();

        DatabasePath = databasePath;

        MainPage = new MainPage();
    }

so what I'm trying to do here is access the database from the database path, leaving the databasePath open since Android, IOS and UWP are all different, according to what I've been reading. Later I add the database name as I will show below the steps.


At this point, I tweak the codes in each to the following :

Android

MainActivity.cs

    private string dbName;
    private string folderPath;
    private string dbPath;

    protected override void OnCreate(Bundle savedInstanceState)
    {
          base.OnCreate(savedInstanceState);

        dbName = "MyDatabase.db3";
        folderPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        dbPath = Path.Combine(folderPath, dbName);

        CopyDatabase();

        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        LoadApplication(new App(dbPath));
    }

    protected void CopyDatabase()
    {
        // Check if your DB has already been extracted.
        if (!File.Exists(dbPath))
        {

            using (BinaryReader br = new BinaryReader(Android.App.Application.Context.Assets.Open(dbName)))
            {
                using (BinaryWriter bw = new BinaryWriter(new FileStream(dbPath, FileMode.Create)))
                {
                    byte[] buffer = new byte[2048];
                    int len = 0;
                    while ((len = br.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        bw.Write(buffer, 0, len);
                    }
                }
            }
        }
    }

Adding my .db3 database to "Assets" Folder in the Android build


IOS

AppDelegate.cs

  public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {

        string dbName = "MyDatabase.db3";
        string folderPath =                                                                                                              
        Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal),"..", "Library");
        string dbPath = Path.Combine(folderPath, dbName);

        global::Xamarin.Forms.Forms.Init();
        LoadApplication(new App(dbPath));

        return base.FinishedLaunching(app, options);
    }

Adding my .db3 database to "Resources" Folder in the IOS build


UWP

MainPage.xaml.cs

 public MainPage()
    {
        this.InitializeComponent();

        string dbName = "MyDatabase.db3";
        string folderPath = ApplicationData.Current.LocalFolder.Path;
        string dbPath = Path.Combine(folderPath, dbName);
        LoadApplication(new XamarinWhitey.App(dbPath));
    }

Adding my .db3 database to "Assets" Folder in the UWP build


I expected this to work, though to my surprise It isn't working.

When I run the app (on any device) I've been trying different methods for over a week now and I Need some guidance and help to figure this out.

Thanks all !

  • you have to copy the database file from your app bundle to the destination path before you can open it – Jason Apr 03 '21 at 15:12
  • Hi, Could you elaborate a bit more? I'm still relatively new to Xamarin and all my programming experience is from Game Development. I'm still adjusting :) I've manually copied the database to each Platform's folder as I explained above (so I've copied it to 3 locations). Perhaps this is not what you mean. Best regards and thanks ! – KnottyDreadLox Apr 03 '21 at 15:18
  • I followed https://stackoverflow.com/questions/18715613/use-a-local-database-in-xamarin by adding the copy database, though It still Isn't working :/ – KnottyDreadLox Apr 03 '21 at 18:40
  • You need to be more specific than that - "isn't working" doesn't tell me anything useful – Jason Apr 03 '21 at 18:49
  • Hi again, I figured it out and fixed my question for anyone else who comes across this :) Thank you @Jason for the help :) – KnottyDreadLox Apr 05 '21 at 11:19

0 Answers0