public class DbHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "mydatabase.db";
private static final String DB_DIRECTORY = "/data/data/com.example.sampleprogname/databases/";
private static final String DB_FILEPATH = DB_DIRECTORY + DB_NAME;
private static final int DB_VERSION = 4;
private SQLiteDatabase db;
private Context context;
private static DbHelper dbHelper;
public static DbHelper getInstance(Context context) {
if (dbHelper == null) {
// Хотя context приходит от конкретной активити, но это контекст application
dbHelper = new DbHelper(context);
}
return dbHelper;
}
private DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.context = context;
if (dbExists()) {
opendDb();
} else {
createDb();
}
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public void createDb() {
if(!dbExists()) {
this.getReadableDatabase();
try {
copyDbFromAssetsToDevice();
} catch(IOException ex) {
Log.e("db-copy", "Не удалось скопировать БД на устройство: " + ex.getMessage());
}
}
}
private void copyDbFromAssetsToDevice() throws IOException {
try {
InputStream istream = context.getAssets().open(DB_NAME);
OutputStream ostream = new FileOutputStream(DB_FILEPATH);
byte[] buffer = new byte[1024];
int length;
while ((length = istream.read(buffer)) > 0){
ostream.write(buffer, 0, length);
}
ostream.flush();
ostream.close();
istream.close();
} catch (Exception e) {
Log.e("db-copy", e.getMessage());
}
}
private boolean dbExists() {
boolean dbExist = false;
try {
File dbfile = new File(DB_FILEPATH);
dbExist = dbfile.exists();
} catch(SQLiteException e) {
Log.e("Database does not exists", e.getMessage());
}
return dbExist;
}
public void opendDb() throws SQLException {
db = SQLiteDatabase.openDatabase(DB_FILEPATH, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void closeDb() {
if(db != null) {
db.close();
}
super.close();
}
}