【问题标题】:Creating SQLite database on Internal storage ANDROID在内部存储 ANDROID 上创建 SQLite 数据库
【发布时间】:2017-12-19 07:44:21
【问题描述】:

我正在尝试在我的 Xamarin 应用程序中的内部存储上创建一个 SQLIte 数据库。我正在为离线环境创建一个系统,其中至少有 3 个应用程序与共享数据互连。因此,如果一个应用程序创建了一些数据,那么另一个应用程序应该能够读取这些数据。

Database 项目是一个可移植的类库,我计划将其包含在所有三个应用程序中。

我的 DbHelper 如下:

public Database()
{
    string folder = "/data/data/Anchor.Main";
    _dbPath = System.IO.Path.Combine(folder, "Anchor.db");

    try
    {
        if (!System.IO.Directory.Exists(folder))
        {
            System.IO.Directory.CreateDirectory(folder); //Getting error here
        }

        _connection = new SQLiteConnection(_dbPath);
        _connection.CreateTable<Orders>();
        _connection.CreateTable<Items>();    

    }
    catch(Exception ex)
    {  }

}

我收到错误提示

对路径“/data/data/Anchor.Main”的访问被拒绝。

下面是堆栈跟踪

在 System.IO.Directory.CreateDirectoriesInternal(System.String 路径) [0x0004b] 在 :0 处 System.IO.Directory.CreateDirectory (System.String path) [0x00075] in :0 在 anchorapp.db.Helper.Database..ctor()[0x0002e]

我知道这是因为权限,但我需要设置哪些权限才能从 PCL 写入内部存储?

【问题讨论】:

    标签: android sqlite xamarin xamarin.android


    【解决方案1】:

    您正在访问“/data/data/Anchor.Main”的Android系统文件夹。 您的应用内部存储将在

    /data/data/@PACKAGE_NAME@/files
    

    可以使用以下代码获取存放数据库的文件夹:

    // Equal to /data/data/@PACKAGE_NAME@/files
    var homePath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    _dbPath = System.IO.Path.Combine(homePath, "Anchor.db");
    _connection = new SQLiteConnection(_dbPath);
    

    【讨论】:

    • 我可以这样做,但我需要其他应用程序才能访问此应用程序创建的数据库。是否可以从另一个数据库创建的数据库中读取数据?
    • 您可以在您的清单中定义 android:sharedUserId 以使 2 个应用程序共享数据。但是,您应该考虑您的应用程序是否真的需要使用这种方法。查看 ContentProvider,看看它是否可以首先满足您计划对您的应用执行的操作。
    • 我尝试使用内容提供程序,但导致了不同的错误stackoverflow.com/questions/45074287/… 我肯定需要访问数据库,至少有 3 个应用程序中的 1 个应用程序。如何使用 sharedId 进行操作。
    【解决方案2】:

    Android 和 iOS 不能这样工作。每个平台都将应用程序保存在沙盒环境中。如果您想在您的应用中创建和存储数据,您需要创建如下示例的路径:

    var docFolder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    _dbPath = System.IO.Path.Combine(docFolder, "Anchor.db");
    

    同时在你的 Android 项目中设置 ReadExternalStorage 和 WriteExternalStorage 的权限

    您可以在公共文件夹中创建数据库,而不是写入私人文件夹。为此,docFolder 将更改为:

    var docFolder = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, "YourDirectoryName");
    

    请注意,如果您这样做,每个人都可以看到并打开数据库。

    【讨论】:

    • 我可以这样做,但我需要其他应用程序才能访问此应用程序创建的数据库。是否可以从另一个数据库创建的数据库中读取数据?
    【解决方案3】:

    我通过在我的项目中创建一个 sharedId 并使用 SharedContext 访问由其他应用创建的数据库来做到这一点

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多