Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it ok to create ORMLite database helper in Application class?

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.

like image 404
Alex Avatar asked Nov 21 '11 08:11

Alex


1 Answers

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.

like image 121
Gray Avatar answered Nov 15 '22 18:11

Gray