I recommend to use the LoaderManager to query data from the database in the background.
The most simple query in a loader would be that:
public class CustomLoader extends AsyncTaskLoader<List<? extends DbBase>> {
private static final String LOG_TAG = CustomLoader.class.getSimpleName();
// DbBase is the parent class of all ORMLite data objects.
private List<? extends DbBase> mData;
public CustomLoader(Context context) {
super(context);
}
@Override
public List<? extends DbBase> loadInBackground() {
return DatabaseAdapter.getInstance().getORMLiteObjectDao().queryForAll();
}
@Override
public void deliverResult(List<? extends DbBase> data) {
if (isReset()) {
return;
}
mData = data;
if (isStarted()) {
super.deliverResult(data);
}
}
@Override
protected void onStartLoading() {
if (mData != null) {
deliverResult(mData);
}
if (takeContentChanged() || mData == null) {
forceLoad();
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
@Override
protected void onReset() {
// Ensure the loader has been stopped.
onStopLoading();
// At this point we can release the resources associated with 'mData'.
if (mData != null) {
mData = null;
}
}
}
As I did quite some heavy transactions (update/delete/inserts) I used an ExecutorService
, created a chached ThreadPool and executed the transaction within the executor:
final Callable<SyncResult> transactionCall = new Callable<SyncResult>() {
@Override
public SyncResult call() throws Exception {
// do the sql magic
}
};
MyApplication.execute(new Runnable() {
@Override
public void run() {
try {
TransactionManager.callInTransaction(DatabaseAdapter.getInstance().getConnectionSource(), transactionCall);
} catch (SQLException e) {
Log.e(LOG_TAG, "Error in DB transaction", e);
}
}
});
As long transactions will result in a locked database, I recommend to enable "write ahead" (requires API 11!).
SQLiteDatabase db = mHelper.getWritableDatabase();
if (db != null && db.enableWriteAheadLogging()) { // requires API 11!
Log.d(LOG_TAG, "Write ahead enabled!");
mHelper.getRuntimeExceptionDao(ORMliteDataClass.class).queryRaw("PRAGMA journal_mode = \"WAL\"");
}