Android Application – Use Pre-Loaded Database

Hi Folks,

To use a pre-loaded database, place your database in assets directory (optional; you can use external storage too) of your app. Copy to /data/data/<your package name>/databases/ directory.

Caution: While copying ensure directory structure is present as “new FileOutputStream(filename)” will throw “FileNotFound Exception“. You can use “myfile.mkdirs()” to create directory stucture.

Here is an example code –

//Ifdatabase did not exist, try copying existing databasefrom assets folder.
try {
    InputStream myinput = mContext.getAssets().open(DATABASE_NAME);
    String outfilename = DATABASE_PATH + DATABASE_NAME;
    OutputStream myoutput = new FileOutputStream(outfilename);
    byte[] buffer = new byte[1024];
    int length;
    while((length = myinput.read(buffer))>0){
         myoutput.write(buffer,0, length);
    }
    myoutput.flush();
    myoutput.close();
    myinput.close();
} 
catch (IOException e){
    e.printStackTrace();
}

Note: I’ve found above solution after searching on internet for sometime. I’m not sure if it is the best. Please do let me know if you know something better.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s