从资产文件夹复制数据库到数据库文件夹

10

在主活动中,我有这个方法,它将文件从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_metadatalocal表。 - minhaz
@new Ques 请检查我的回答,它可能会有所帮助。 - Trikaldarshiii
1个回答

20

我的方法

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

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

10
我会尽力进行翻译,请确认以下内容是否正确:我认为在 DB_PATH = cw.getFilesDir().getAbsolutePath()+ "/Database/" 这段代码中,最后一个单词 Database 应该改为 /databases/ - mehmet
实际上,根据@CommonsWare在回答这个问题的备选帖子中的建议,路径不应该被硬编码。也就是说,不要输入"/Database/";相反,使用 getDatabasePath() 来推导数据库文件的路径。 - Jorge
获取数据库路径:getDatabasePath(DATABASE_NAME).getAbsolutePath(); - live-love
1
这在我的情况下不起作用。 - Bipin Bharti

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接