Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An abstract generic loader that can be used to fetch data from a sqlite database. It handles the database connection and delivering of results to any class that implements LoaderCallbacks. It is up to the child class to implement doInBackground(...) thus allowing the child to decide what data to load. This class does have a dependency to the Gre…
package com.mdrabic.content;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.content.AsyncTaskLoader;
import com.docdock.android.R;
import com.docdock.android.db.DaoMaster;
import com.docdock.android.db.DaoSession;
import java.util.List;
/**
* A generic loader that provides basic functionality for fetching data from the database. It is
* left up to its' subclasses what data should be loaded.
*
* @author mike
*/
public abstract class EntityLoader<T> extends AsyncTaskLoader<List<T>> {
protected List<T> mEntityList;
protected Context mContext;
protected SQLiteDatabase mDB;
protected DaoMaster mDaoMaster;
protected DaoSession mDaoSession;
public EntityLoader(Context context) {
super(context);
mContext = context;
}
/**
* Connects to the database by initializing appropriate database members and
* grabbing an instance of a SQLiteDatabase.
*/
protected void connectToDb() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(mContext,
mContext.getString(R.string.database), null);
mDB = helper.getWritableDatabase();
mDaoMaster = new DaoMaster(mDB);
mDaoSession = mDaoMaster.newSession();
helper.close();
}
/**
* Closes the database and sets all db related members to null to influence the
* garbage collector.
*/
protected void disconnectFromDb() {
mDB.close();
mDaoMaster = null;
mDaoSession = null;
}
@Override
public abstract List<T> loadInBackground();
@Override
public void deliverResult(List<T> data) {
mEntityList = data;
if (isStarted()) {
super.deliverResult(data);
}
}
@Override
protected void onStartLoading() {
if (takeContentChanged() || mEntityList == null) {
forceLoad();
} else {
deliverResult(mEntityList);
}
}
@Override
protected void onReset() {
super.onReset();
// Ensure the loader is stopped
onStopLoading();
if (mEntityList != null) {
mEntityList = null;
}
}
@Override
protected void onStopLoading() {
cancelLoad();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment