Page MenuHomec4science

AssetDatabaseOpenHelper.java
No OneTemporary

File Metadata

Created
Wed, Jan 29, 20:37

AssetDatabaseOpenHelper.java

package ch.epfl.pharma.database;
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.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class AssetDatabaseOpenHelper extends SQLiteOpenHelper {
private static final String TAG = AssetDatabaseOpenHelper.class.getName();
// db loaded from /assets, hence version=1
private static final int DB_VERSION = 1;
private SQLiteDatabase mDatabase;
private final Context mContext;
private String mDbName;
private File dbFile;
public AssetDatabaseOpenHelper(Context context, String dbName) {
super(context, dbName, null, DB_VERSION);
this.mContext = context;
this.mDbName = dbName;
this.dbFile = mContext.getDatabasePath(mDbName);
}
public void createDatabase() throws IOException {
boolean dbExist = databaseExists();
if (dbExist) {
Log.i(TAG, "Database exists");
// do nothing - database already exists
} else {
Log.i(TAG, "Database does not exist");
// create an empty database for the app
this.getReadableDatabase();
// override with the populated one
copyDatabase();
}
}
public boolean databaseExists() {
SQLiteDatabase checkDb = null;
if (dbFile.exists()) {
try {
checkDb = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database cannot be openend
Log.w(TAG, "Something went wront while reading database");
}
}
if (checkDb != null) {
checkDb.close();
return true;
}
return false;
}
private void copyDatabase() throws IOException {
InputStream mInput = mContext.getAssets().open(mDbName);
OutputStream mOutput = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
int len;
while ((len = mInput.read(buffer)) > 0) {
mOutput.write(buffer, 0, len);
}
mOutput.flush();
mOutput.close();
mInput.close();
}
public void openDatabaseReadOnly() throws SQLException {
mDatabase = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
public void openDatabase() throws SQLException {
if (mDatabase == null) {
mDatabase = SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READWRITE);
} else {
Log.d(TAG, "database already openend");
}
}
@Override
public synchronized void close() {
if (mDatabase != null) {
mDatabase.close();
}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public SQLiteDatabase getDatabase() {
return mDatabase;
}
}

Event Timeline