Ad

Sunday, July 7, 2013

How to copy sqlite db from Asset Folder in Android ?

 1. Put the dbfile in the asset folder.

2. Create an instance to the dbFile.

File dbfile=new File(parentfolder,dbfile); (we can choose any folder as parent folder)

3. Check whether db is existing or not. if not copy it to the folder.

if (!dbfile.exists()) {
try {
copyDatabase(dbfile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}

private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
 
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
 
os.flush();
os.close();
is.close();
}

No comments:

Post a Comment