【问题标题】:copy database from assets to databases folder [duplicate]将数据库从资产复制到数据库文件夹[重复]
【发布时间】:2013-09-19 07:06:05
【问题描述】:

在主要活动中,我有这个方法将文件从assets 复制到databases 文件夹:

try{
    // CHECK IS EXISTS OR NOT
    SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/com.henanet.dalel/databases/mydb.sqlite",null, 0);
    dbe.close();
    // COPY IF NOT EXISTS
    AssetManager am = getApplicationContext().getAssets();
    OutputStream os = new FileOutputStream("/data/data/com.henanet.dalel/databases/mydb.sqlite");
    byte[] b = new byte[100];
    int r;
    InputStream is = am.open("mydb.sqlite");
    while ((r = is.read(b)) != -1) {
        os.write(b, 0, r);
    }
    is.close();
    os.close();
}
catch(Exception e)
{

}

但是一旦用户安装了应用程序,他就会在 LogCat 中得到这个错误:

09-14 22:57:25.694: I/Database(19903): sqlite returned: error code = 14, msg = cannot               open file at source line 25467
09-14 22:57:25.694: E/Database(19903): sqlite3_open_v2("/data/data/com.henanet.dalel/databases/mydb.sqlite", &handle, 2, NULL) failed

【问题讨论】:

  • 你是如何创建你试图从'/data/data'文件夹打开的数据库的。 Android 期望 android_metadata, local 每个数据库中的表。
  • @new Ques 检查我的答案可能有帮助

标签: android database copy


【解决方案1】:

我的方法

使用以下获取您的数据库路径

ContextWrapper cw =new ContextWrapper(getApplicationContext());
DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/databases/"; //edited to databases

那你可以往这边走

private void copyDataBase()
    {
        Log.i("Database",
                "New database is being copied to device!");
        byte[] buffer = new byte[1024];
        OutputStream myOutput = null;
        int length;
        // Open your local db as the input stream
        InputStream myInput = null;
        try
        {
            myInput =myContext.getAssets().open(DB_NAME);
            // transfer bytes from the inputfile to the
            // outputfile
            myOutput =new FileOutputStream(DB_PATH+ DB_NAME);
            while((length = myInput.read(buffer)) > 0)
            {
                myOutput.write(buffer, 0, length);
            }
            myOutput.close();
            myOutput.flush();
            myInput.close();
            Log.i("Database",
                    "New database has been copied to device!");


        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

【讨论】:

  • 我认为在DB_PATH =cw.getFilesDir().getAbsolutePath()+ "/Database/"最后一句话,数据库应该是/databases/
  • 实际上,根据回答此问题的替代帖子中的@CommonsWare 建议,路径永远不应该被硬编码。即输入"/Database/";相反,使用getDatabasePath() 导出数据库文件的路径。
  • 获取db路径:getDatabasePath(DATABASE_NAME).getAbsolutePath();
  • 这在我的情况下不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-02
  • 2013-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-20
  • 1970-01-01
相关资源
最近更新 更多