【发布时间】:2017-08-25 02:04:59
【问题描述】:
我在我的项目中创建了一个包含一些数据的 sqlite 文件,但我不知道如何将它链接到我的应用程序。我希望数据可以加载到 Android 模拟器上。
我找到一个2015年发布的教程,它不再起作用,例如在新建一个FileAccessHelper类后找不到GetLocalFilePath函数。并且教程项目似乎使用了旧版本的 SQLite.net-PCL 包,因为教程项目中使用了 SQLite.Net.Platform.XamarinAndroid,而这个包不再存在。有什么想法吗?
http://arteksoftware.com/deploying-a-database-file-with-a-xamarin-forms-app/
这是教程中的代码:
[Activity (Label = "People", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
global::Xamarin.Forms.Forms.Init (this, bundle);
string dbPath = FileAccessHelper.GetLocalFilePath ("people.db3");
LoadApplication (new People.App (dbPath, new SQLitePlatformAndroid ()));
}
}
FileAccessHelper.cs
public class FileAccessHelper
{
public static string GetLocalFilePath (string filename)
{
string path = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
string dbPath = Path.Combine (path, filename);
CopyDatabaseIfNotExists (dbPath);
return dbPath;
}
private static void CopyDatabaseIfNotExists (string dbPath)
{
if (!File.Exists (dbPath)) {
using (var br = new BinaryReader (Application.Context.Assets.Open ("people.db3"))) {
using (var bw = new BinaryWriter (new FileStream (dbPath, FileMode.Create))) {
byte[] buffer = new byte[2048];
int length = 0;
while ((length = br.Read (buffer, 0, buffer.Length)) > 0) {
bw.Write (buffer, 0, length);
}
}
}
}
}
}
【问题讨论】:
-
您应该使用“初始化脚本”而不是固定的 sqlite 文件 - 基本上是从代码初始化数据库的调用。由于(我想)您已经或多或少地使用数据库进行了管理(甚至可能是跨平台),因此它只会在您的第一次启动过程中添加一个步骤。
标签: c# sqlite xamarin xamarin.forms