Skip to content

Instantly share code, notes, and snippets.

@wontondon
Created October 8, 2011 03:12
Show Gist options
  • Star 32 You must be signed in to star a gist
  • Fork 9 You must be signed in to fork a gist
  • Save wontondon/1271795 to your computer and use it in GitHub Desktop.
Save wontondon/1271795 to your computer and use it in GitHub Desktop.
Copy sqlite database from assets dir - Android
package com.javatarts.basketballgm.data;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
public class AssetDatabaseOpenHelper {
private static final String DB_NAME = "asset.db";
private Context context;
public AssetDatabaseOpenHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!dbFile.exists()) {
try {
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
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();
}
}
Copy link

ghost commented Aug 15, 2015

Hi, I have a problem with my code:
When I was running my program on the simulator:
In logcat:
"No such file or directory (2)"
please help me .

@MinThantZin
Copy link

: (10) Failed to do file read, got: 0, amt: 100, last Errno: 2
help me

@shaahu
Copy link

shaahu commented Sep 20, 2019

Awesome! Thanks!

@RakibOFC
Copy link

RakibOFC commented Feb 9, 2023

Thank you brother <3

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment