Geralt_Encore
Geralt_Encore

Reputation: 3771

OrmLite multithreading

I need to have an access to helper not only from Activities, but, for example, from BroadcastReceivers and AsyncTasks. Am I right, that if I am using OrmLiteBaseActivity to approach it is to use this methods:

OpenHelperManager.getHelper(context, DatabaseHelper.class);
OpenHelperManager.releaseHelper();

inside not Activity classes?

EDIT:

I understand that helper lifecycle is handled by OrmLiteBaseActivity. What I am asking is how to handle helper lifecycle outside of activities. For example, I need an access to database from BroadcastReceiver or AsyncTask. Is it a right way to achieve this using OpenHelperManager.getHelper(context, DatabaseHelper.class);, when I am starting some database stuff in another thread, and OpenHelperManager.releaseHelper();, when I've done all database work and want to release helper?

Upvotes: 4

Views: 2103

Answers (1)

Gray
Gray

Reputation: 116908

Am I right, that if I am using OrmLiteBaseActivity to approach it is to use this methods...

Yes, using the OpenHelperManager.getHelper(...) and releaseHelper() methods is the right way to do this. To quote from the ORMLite Android docs:

If you do not want to extend the OrmLiteBaseActivity and other base classes then you will need to duplicate their functionality. You will need to call OpenHelperManager.getHelper(Context context, Class openHelperClass) at the start of your code, save the helper and use it as much as you want, and then call OpenHelperManager.release() when you are done with it. You will probably want to have something like the following in your classes:

The sample code in the docs is:

private DatabaseHelper databaseHelper = null;

@Override
protected void onDestroy() {
    super.onDestroy();
    if (databaseHelper != null) {
        OpenHelperManager.releaseHelper();
        databaseHelper = null;
    }
}

private DBHelper getHelper() {
    if (databaseHelper == null) {
        databaseHelper =
            OpenHelperManager.getHelper(this, DatabaseHelper.class);
    }
    return databaseHelper;
}

Upvotes: 5

Related Questions