public void copyAttachedDatabase(Context context, String databaseName) { final File dbPath = context.getDatabasePath(databaseName); // If the database already exists, return if (dbPath.exists()) { return; } // Make sure we have a path to the file dbPath.getParentFile().mkdirs(); // Try to copy database file try { final InputStream inputStream = context.getAssets().open(databaseName); final OutputStream output = new FileOutputStream(dbPath); byte[] buffer = new byte[1024]; int length; while ((length = inputStream.read(buffer)) > 0) { output.write(buffer, 0, length); } output.flush(); output.close(); inputStream.close(); } catch (IOException e) { Log.e("Failed to open file", e); } }
private boolean executeMigrations(SQLiteDatabase db, int oldVersion, int newVersion) { boolean migrationExecuted = false; try { final List<String> files = Arrays.asList(Cache.getContext().getAssets().list(MIGRATION_PATH)); Collections.sort(files, new NaturalOrderComparator()); db.beginTransaction(); try { for (String file : files) { try { final int version = Integer.valueOf(file.replace(".sql", "")); if (version > oldVersion && version <= newVersion) { executeSqlScript(db, file); migrationExecuted = true; Log.i(file + " executed succesfully."); } } catch (NumberFormatException e) { Log.w("Skipping invalidly named file: " + file, e); } } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } catch (IOException e) { Log.e("Failed to execute migrations.", e); } return migrationExecuted; }
private void executeSqlScript(SQLiteDatabase db, String file) { InputStream stream = null; try { stream = Cache.getContext().getAssets().open(MIGRATION_PATH + "/" + file); if (Configuration.SQL_PARSER_DELIMITED.equalsIgnoreCase(mSqlParser)) { executeDelimitedSqlScript(db, stream); } else { executeLegacySqlScript(db, stream); } } catch (IOException e) { Log.e("Failed to execute " + file, e); } finally { IOUtils.closeQuietly(stream); } }