VS2017 Android和SQLite

时间:2017-05-26 06:38:36

标签: android visual-studio android-sqlite

也许是一个愚蠢的问题,但我无法在任何地方找到答案!

我的应用程序中有一个sqlite预先填充的数据库,我需要在用户安装应用程序时将其复制到设备,我在VS2017的Assets文件夹中有数据库,并将其标记为嵌入式资源,但我可以&# 39;似乎找到了正确的途径来访问它。

有人能指出我正确的方向吗?我在这里是正确的道路还是还有其他一些需要在某处发生的魔法?

由于 迪安

1 个答案:

答案 0 :(得分:1)

首先在设备外部存储中创建一个工作目录

public void createDirectory()
{
    bool isExists=false;
    string folderExternal;

    try
    {
        // folder path
        folderExternal = "/mnt/sdcard/Sample";

        // checking folder available or not
        isExists= System.IO.Directory.Exists(folderExternal);

        // if not create the folder
        if(!isExists)
        System.IO.Directory.CreateDirectory(folderExternal);

        folderExternal = "/mnt/sdcard/Sample/WorkingDB";
        isExists = System.IO.Directory.Exists(folderExternal);

        if(!isExists)
            System.IO.Directory.CreateDirectory(folderExternal);
    }
}

然后从资产文件夹

复制数据库
public void CopyDBFileFromAssetFolder()
{
    try{
        //checking file exist in location or no
        if (!File.Exists (Constants.DatabasebFilePath))
        {    
            //display progress bar or loader animation
            // Java thread is used for creating or copying
            // database file because this will not make the program non responsive

            new Java.Lang.Thread(() =>
            {
                // calling data from Asset folder
                using (var asset =  Assets.Open ("Empty_DB.db"))
                using (var dest = File.Create ( AppGlobal.DatabasebFilePath))
                {
                    // copying database from Asset folder to external storage device
                    asset.CopyTo (dest);
                }

                RunOnUiThread(() => onSuccessfulLogin());
            }).Start();
        }

    } catch (System.Exception ex) {
        //handle exception
    }
}