如何使用Xamarin.from应用程序部署数据库文件? [英] How to deploy a database file with a Xamarin.from app?

查看:103
本文介绍了如何使用Xamarin.from应用程序部署数据库文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在项目中创建了一个带一些数据的sqlite文件,但是我不知道如何将其链接到我的应用程序.我希望数据可以加载到Android模拟器上.

I created a sqlite file in my project with some data in it, but I don't know how to link it to my app. I expect the data could be loaded on a Android simulator.

我发现了一个发布于2015年的教程,它不再起作用,例如在新建FileAccessHelper类后找不到GetLocalFilePath函数.本教程项目似乎使用旧版本的SQLite.net-PCL软件包,因为本教程项目中使用了SQLite.Net.Platform.XamarinAndroid,而该软件包已不存在.有什么想法吗?

I found a tutorial which was published in 2015, it works no longer, such as GetLocalFilePath function cannot be found after new a FileAccessHelper Class. And the tutorial project seemed using an olde version of SQLite.net-PCL package, because SQLite.Net.Platform.XamarinAndroid was used in the tutorial project, while this package is no longer exist. Any ideas?

http://arteksoftware.com/使用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

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);
                    }
                }
            }
        }
    }
}

推荐答案

如果要从Xamarin.Forms调用该方法,则需要为每个平台实现一个接口,但是我将不做任何详细介绍在此示例中工作.这是有关

You will need to implement an Interface for each platform if you are wanting to call the method from Xamarin.Forms but I will not go into detail on how all that works in this example. Here are the Xamarin docs on the topic of the DependencyService used below.

对于Android,您需要将数据库文件放置在Assets文件夹中.这是您在Android项目中需要的用于复制数据库并返回其路径的接口的代码:

For Android you will need to place the DB file in the Assets folder. This is the code you will need in your Android project for the interface that copies the DB and return its path:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.Droid
{
    class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var docFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var dbFile = Path.Combine(docFolder, databaseName); // FILE NAME TO USE WHEN COPIED
            if (!File.Exists(dbFile))
            {
                FileStream writeStream = new FileStream(dbFile, FileMode.OpenOrCreate, FileAccess.Write);
                await Forms.Context.Assets.Open(databaseName).CopyToAsync(writeStream);
            }
            return dbFile;
        }
    }
}

对于UWP,您需要将数据库文件放置在根文件夹中. UWP项目中用于复制文件并返回路径的界面应如下所示:

For UWP you will want to place the DB file in the root folder. The interface in your UWP project that copies the file and returns the path should look like this:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.UWP
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String filename = "MyLite.db";
            bool isExisting = false;
            try
            {
                StorageFile storage = await ApplicationData.Current.LocalFolder.GetFileAsync(filename);
                isExisting = true;
            }
            catch (Exception)
            {
                isExisting = false;
            }
            if (!isExisting)
            {
                StorageFile databaseFile = await Package.Current.InstalledLocation.GetFileAsync(filename);
                await databaseFile.CopyAsync(ApplicationData.Current.LocalFolder, filename, NameCollisionOption.ReplaceExisting);
            }
            return Path.Combine(ApplicationData.Current.LocalFolder.Path, filename);
        }
    }
}

对于iOS,您需要将数据库文件放置在Resources文件夹中.这是您的iOS项目中界面的代码:

For iOS you will want to place the DB file in your Resources folder. Then this is the code in your iOS project for the interface:

[assembly: Xamarin.Forms.Dependency(typeof(FileAccessHelper))]
namespace MyNamespace.iOS
{
    public class FileAccessHelper : MyXamarinFormsPage.IFileAccessHelper
    {
        public async Task<String> GetDBPathAndCreateIfNotExists()
        {
            String databaseName = "MyLite.db";
            var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(documentsPath, databaseName);
            if (!File.Exists(path))
            {
                var existingDb = NSBundle.MainBundle.PathForResource("MyLite", "db");
                File.Copy(existingDb, path);
            }
            return path;
        }
    }
}

然后可以通过执行以下操作从您的Xamrin.Forms项目中调用它:

It can then be called from your Xamrin.Forms project by doing this:

public class MyXamarinFormsPage
{
    public MyXamarinFormsPage()
    {
        String DBPath = await DependencyService.Get<IFileAccessHelper>().GetDBPathAndCreateIfNotExists()
        //Store string for path
    }

    public interface IFileAccessHelper
    {
        Task<String> GetDBPathAndCreateIfNotExists();
    }
}

这篇关于如何使用Xamarin.from应用程序部署数据库文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆