Tuesday, October 26, 2010

Copying Larger database files in ANDROID Application

If you are trying to import or copy an already existing database ( More than 1Mb in size) file to your application then you will certainly get the following error when you are trying to copy the database.

D/asset (909): Data exceeds UNCOMPRESS_DATA_MAX (1424000 vs 1048576) 
 
Due to the fact that there is a file size limit (upto 1 MB) on resources in the raw or assets folders.
 
Finally it indicates that you can not copy the file which is >1 MB into your application at runtime.
 
I faced this problem when i need to import an 1.5 MB database file into application.
I solved in the following way.
 
1) Split the files.  I used the linux split command to split the binary database file 
into a maximum of 1048576 bytes. 
 
The command is:
split inputfile -b 1048576 outfileprefix 
and the files come out as outfileprefixaa, outfileprefixab, etc.  

2)Copy these files into my raw resource folder and set up my code to 
create and then close a database automatically using SQLiteOpenHelper 
and then to run the following method: 
 
 private void copyDatabase() throws IOException{
       
        OutputStream databaseOutputStream = new 
FileOutputStream("/data/data/com.domain.app/databases/app.db");
         InputStream databaseInputStream;
       
        byte[] buffer = new byte[1024];
        int length;
       
        databaseInputStream = 
databaseOpenHelperContext.getResources().openRawResource(R.raw.datafileaa);
        while ( (length = databaseInputStream.read(buffer)) > 0 ) {
            databaseOutputStream.write(buffer);
        }
        databaseInputStream.close();
       
        databaseInputStream = 
databaseOpenHelperContext.getResources().openRawResource(R.raw.datafileab);
        while ( (length = databaseInputStream.read(buffer)) > 0 ) {
            databaseOutputStream.write(buffer);
        }
        databaseInputStream .close();        
        databaseOutputStream.flush();
        databaseOutputStream.close();
    } 
This solution works perfectly.  And it's very fast.  My final database 
size on the emulator is 1424000 bytes (about 1.5 MB).  It copies almost 
instantly.  There is no delay when the application first runs.  However, 
remember that the resource files remain installed, and you've copied the 
data to a database. 
 
Good luck to all you database pre-populators and I hope this helps.  I 
welcome any input and correction to this document as I am no expert and 
may be doing something that isn't kosher in my code. 

By this we can copy a larger file into application database.


 
 
 
 

Android Developers Blog

Ram's shared items