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.
-
Define existing database. Like one inside of your app resources or one existing on the device before hand. – HSchmale Mar 29 '20 at 02:20
-
You include the db file in your project, and on app startup will need to copy it to writable folder. – Jason Mar 29 '20 at 02:33
-
HSchmale: DB is in Assets/Resources. – Gurmeet Khalsa Mar 30 '20 at 00:42
-
Jason: I am new to Xamarin, don't know how to copy db file from assets/resources to device folder. Can you provide any code examples. – Gurmeet Khalsa Mar 30 '20 at 00:43
1 Answers
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.
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:

- 10,160
- 1
- 10
- 16