[Android SDK]Can't copy external database (13MB) from Assets

半世苍凉 提交于 2019-11-29 12:13:56

Use SQLiteAssetHelper, which has a debugged version of the package-the-database-with-the-app logic, so you do not need to mess with any of this yourself.

First of all by default asset folder supports max size for db file is 1mb.

You need to divide your database into parts.

Download HJSplit and divide your database into small parts like 13MB = 13 parts each of 1MB.

demoDB.sqlitedb= 13MB then

demodb..sqlitedb.001
demodb..sqlitedb.002
demodb..sqlitedb.003
demodb..sqlitedb.004
...
...
demodb..sqlitedb.013

Then use the following code to merge your database.

private void copyDataBase() throws IOException {
        AssetManager am = mContext.getAssets();
        OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] b = new byte[1024];
        String[] files = am.list("");
        Arrays.sort(files);
        int r;
        for (int i = 1; i <= 9; i++) {
            InputStream is = am.open("demoDB.sqlitedb.00" + i);
            while ((r = is.read(b)) != -1) {
                os.write(b, 0, r);
            }
            Log.i("BABY_DATABASE_HELPER", "Copying the database (part " + i
                    + " of 9)");
            is.close();
        }
        os.close();
    }
private void copyDataBase() throws IOException {
    AssetManager am = getAssets();
   OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);

    byte[] b = new byte[1024];
    String[] files = am.list("");
    Arrays.sort(files);
    int r;
    for (int i = 1; i <=21; i++) {
        InputStream is;

        if ( i < 10){
            System.out.println("coping file demoDB.sqlitedb.00"+i );
             is = am.open("demoDB.sqlitedb.00" + i);
        }else{
            System.out.println("coping file demoDB.sqlitedb.0"+i );
             is = am.open("demoDB.sqlitedb.0" + i);
       }
        while ((r = is.read(b)) != -1) {
            os.write(b, 0, r);
        }
        is.close();
    }
    os.close();
}

I know this was answered but I ran into something like this while creating tests where I wanted to store a particular database with faults in it to test bad data. Problem was test database was not found at all in the assets. To even see it I had to do this:

InputStream is = mContext.createPackageContext("com.activities.tests", Context.CONTEXT_IGNORE_SECURITY).getAssets().open("mydb.db");

By ignoring the security you can see it and then take the inputstream and save it to an external directory.

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