Sqlite database not copied from asset folder Android

北慕城南 提交于 2020-01-20 08:37:16

问题


I am trying to copy a database named "adinpect" from the asset folder to the application databases folder, but it is not working...

Code (in main activity onCreate(), just for testing):

 try {
        String destPath = "/data/data/" + getPackageName() + "/databases";
        File f = new File(destPath);

        if (!f.exists()) {

            f.mkdirs();
            f.createNewFile();
            //---copy the db from the assets folder into the databases folder---
            CopyDB(getBaseContext().getAssets().open("adinspect"), new FileOutputStream(destPath + "/adinspect"));
        }

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


 public void CopyDB(InputStream inputStream, OutputStream outputStream) throws IOException {

        //---copy 1K bytes at a time---
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        outputStream.close();

}//end copyDB

The "databases" folder is created but there in nothing in it, trying to access it by DDMS.

I do not get any errors.

Any suggestion?

Thanks


回答1:


This code wlll help you to copy DB from assets folder. You can check first if DB exists or not.

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


来源:https://stackoverflow.com/questions/12713640/sqlite-database-not-copied-from-asset-folder-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!