Skip to content

Instantly share code, notes, and snippets.

@pedrovgs
Created March 6, 2017 16:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pedrovgs/da58e4af2a4c437afeeead17fa5ba99f to your computer and use it in GitHub Desktop.
Save pedrovgs/da58e4af2a4c437afeeead17fa5ba99f to your computer and use it in GitHub Desktop.
Working with SQLite in two simple classes
package com.github.pedrovgs.example.storage;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabaseLockedException;
import android.database.sqlite.SQLiteOpenHelper;
import android.support.annotation.NonNull;
import com.github.pedrovgs.example.logger.Logger;
public class SQLDelightStorage {
private static final Object DB_LOCK = new Object();
private final SQLiteOpenHelper openHelper;
public SQLDelightStorage(SQLiteOpenHelper openHelper) {
this.openHelper = openHelper;
}
protected void executeTransaction(Transaction transaction) {
executeTransaction(transaction, new EmptyErrorListener());
}
protected void executeTransaction(Transaction transaction, @NonNull ErrorListener errorListener) {
synchronized (DB_LOCK) {
Logger.d("Start writing a DB transaction");
SQLiteDatabase database = null;
try {
database = openHelper.getWritableDatabase();
database.beginTransaction();
transaction.execute(database);
database.setTransactionSuccessful();
} catch (SQLiteDatabaseLockedException e) {
Logger.e(e.getMessage());
errorListener.onUnrecoverableError();
} finally {
if (database != null) {
database.endTransaction();
database.close();
}
Logger.d("Write DB transaction finished");
}
}
}
protected <T> T read(Read<T> read) {
return read(read, new EmptyErrorListener());
}
protected <T> T read(Read<T> read, @NonNull ErrorListener errorListener) {
synchronized (DB_LOCK) {
Logger.d("Start reading from DB");
T result = null;
SQLiteDatabase database = null;
try {
database = openHelper.getWritableDatabase();
result = read.read(database);
} catch (SQLiteDatabaseLockedException e) {
Logger.e(e.getMessage());
errorListener.onUnrecoverableError();
} finally {
Logger.d("End reading from DB");
if (database != null) {
database.close();
}
}
return result;
}
}
public interface Read<T> {
T read(SQLiteDatabase database);
}
public interface Transaction {
void execute(SQLiteDatabase database);
}
public interface ErrorListener {
void onUnrecoverableError();
}
private static class EmptyErrorListener implements ErrorListener {
@Override public void onUnrecoverableError() {
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
package com.github.pedrovgs.example.storage;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;
import com.github.pedrovgs.example.BuildConfig;
import com.github.pedrovgs.example.storage.ConfigModel;
import com.github.pedrovgs.example.logger.Logger;
import com.github.pedrovgs.example.storage.MetricModel;
import com.github.pedrovgs.example.ReportModel;
public class SQLDelightfulOpenHelper extends SQLiteOpenHelper {
private static SQLDelightfulOpenHelper INSTANCE;
private static final String DB_NAME = "dbname";
private static final int DB_VERSION = BuildConfig.VERSION_CODE;
private static final String REPORT_TIMESTAMP_INDEX =
"CREATE INDEX search_report_timestamp ON report (report_timestamp DESC)";
private static final String REPORT_ID_INDEX = "CREATE INDEX report_id ON metric (report_id)";
public static synchronized SQLDelightfulOpenHelper getInstance(Context context) {
if (INSTANCE == null) {
INSTANCE = new SQLDelightfulOpenHelper(context);
}
return INSTANCE;
}
private SQLDelightfulOpenHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
@Override public void onConfigure(SQLiteDatabase db) {
super.onConfigure(db);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
db.setForeignKeyConstraintsEnabled(true);
}
}
@Override public void onCreate(SQLiteDatabase db) {
Logger.d("Database onCreate method invoked");
createTables(db);
}
@Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion != newVersion) {
dropTables(db);
createTables(db);
}
}
private void createTables(SQLiteDatabase db) {
db.execSQL(ConfigModel.CREATE_TABLE);
db.execSQL(ReportModel.CREATE_TABLE);
db.execSQL(MetricModel.CREATE_TABLE);
db.execSQL(REPORT_TIMESTAMP_INDEX);
db.execSQL(REPORT_ID_INDEX);
}
private void dropTables(SQLiteDatabase db) {
dropTable(db, ConfigModel.TABLE_NAME);
dropTable(db, ReportModel.TABLE_NAME);
dropTable(db, MetricModel.TABLE_NAME);
}
private void dropTable(SQLiteDatabase db, String tableName) {
db.execSQL("DROP TABLE " + tableName);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment