I am trying to create an android application using ORMLite package. I have a few activities and services and also use https://github.com/tomquist/Android-Error-Reporter to be able to receive errors from clients' pdas. ORMLite requires that all activities and services extend OrmLiteBaseActivity etc or add appropriate code to each activity to be able to get database helper and release it after the activity is finished. so this isn't very convenient to add this code to every activity or service. i also have some helper classes which can use database
I also have an application class that holds some global information and methods. So I decided to open ormlite helper in application class and use it through all activities/classes like this:
public class MyApplication extends Application {
private volatile DatabaseHelper databaseHelper = null;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onTerminate() {
if (databaseHelper != null) {
OpenHelperManager.releaseHelper();
databaseHelper = null;
}
super.onTerminate();
}
public DatabaseHelper getHelper() {
if (databaseHelper == null) {
databaseHelper = OpenHelperManager.getHelper(this, DatabaseHelper.class);
}
return databaseHelper;
}
}
and use it in other classes this way:
((MyApplication) getApplicationContext()).getHelper();
do you think it is a good idea to use it this way or there can be some memory leaks or other problems with this? My concern is that onTerminate never works on real devices... I am on the stage of "trying new stuff out" so would like to hear any comments about this to eliminate problems I can get in the future with a wrong approach and not having to rewrite the code.
The overall mechanism looks fine @Alex but as far as I know, onTerminate()
is only used in emulated environments so doesn't have much use. You program gets killed by the Android OS when it terminates on a real device so there is no reason to be worried about memory leaks and the such.
What is most important with your code is that it guarantees a single databaseHelper
instance. Each instance has it's own connection to the database and problems happen when there are more than one (1) connection opened to the database in a program. Sqlite handles multiple threads using the same connection at the same time but it doesn't handle multiple connections well and data inconsistencies may occur.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With