根据您的描述,您在Android项目的Assest中添加了一个sqlite数据库,现在您想使用这个sqlite。
首先,在所有三个PCL、Android和IOS项目中安装Sqlite.net.core,在Android项目中安装SQLite.Net.Platform.XamarinAndroid。
然后在 PCL 中创建接口 IDatabase.cs:
public interface IDatabase
{
SQLite.Net.SQLiteConnection createconnection();
}
在Android中实现该接口获取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();
}
请注意:SQLite.Net.Platform.XamarinAndroid早期版本安装成功。但是,它会抛出错误“Package SQLite.Net.Platform.XamarinAndroidN 3.1.1 is not compatible with monoandroid90 (MonoAndroid,Version=v9.0)”并且包安装会失败。这是一个错误,今天没有解决方案。你可以从this link复制这个dll来添加你的android项目。
更多详细信息,请看:
Use a local database in Xamarin