1

I am trying to use an existing sqlite database in my app. Not sure how to do that. I have seen a few suggestion online but didn't find anything helpful.

1 Answers1

1

According to your description, you add one sqlite database in Assest in Android project, now you want to use this sqlite.

Firstly,install Sqlite.net.core in all three PCL, Android and IOS Projects, SQLite.Net.Platform.XamarinAndroid in Android Project.

enter image description here

Then you create interface IDatabase.cs in PCL:

 public interface IDatabase
{
    SQLite.Net.SQLiteConnection createconnection();
}

Implementing this interface in Android to get SqliteConnection.

public class GetDatabase : IDatabase
{
    public SQLite.Net.SQLiteConnection createconnection()
    {
        var fileName = "SQLite.db3";
        var documentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var path = Path.Combine(documentPath, fileName);

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

        var plat = new SQLite.Net.Platform.XamarinAndroid.SQLitePlatformAndroid();
        var conn = new SQLite.Net.SQLiteConnection(plat, path);

        return conn;
        //var plat = new SQLite.Net.Plataform.XamarinAndroid.SqlitePlatformAndroid();



    }

Please note: SQLite.Net.Platform.XamarinAndroid earlier versions installation was successful. However, it will throw and error “Package SQLite.Net.Platform.XamarinAndroidN 3.1.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0)” and package installation will fail. It’s a bug and solution is not available of today.You can copy this dll from this link to add your android project.

More detailed info, please take a look:

Use a local database in Xamarin

Cherry Bu - MSFT
  • 10,160
  • 1
  • 10
  • 16