Skip to content

Instantly share code, notes, and snippets.

@cirocosta
Created January 19, 2014 00:10
Show Gist options
  • Save cirocosta/8498674 to your computer and use it in GitHub Desktop.
Save cirocosta/8498674 to your computer and use it in GitHub Desktop.
DbPrebuilt.java
public class DbPrebuilt extends SQLiteOpenHelper {
private static final String DB_PATH = "/data/data/my_package/databases/";
private static final String DB_NAME = "my_database_name.db";
private static final String DB_FULL_PATH = DB_PATH + DB_NAME;
private SQLiteDatabase mDatabase;
private final Context mContext;
public DbPrebuilt(Context context){
super(context, DB_NAME, null, 1);
this.mContext = context;
}
public void createDatabase() throws IOException {
boolean dbExists = checkDatabase();
if(dbExists){
//don't do a thing. It already exists
} else {
this.getWritableDatabase();
copyDatabase();
}
}
private boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try {
checkDB = SQLiteDatabase.openDatabase(DB_FULL_PATH, null,
SQLiteDatabase.OPEN_READONLY);
} catch(SQLiteException e){
// database doesnt exists yet
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException {
InputStream inputStream = myContext.getAssets().open(DB_NAME);
OutputStream outputStream = new FileOutputStream(DB_FULL_PATH);
bite[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment