Ormlite setup without using base activities

后端 未结 2 1004
终归单人心
终归单人心 2020-12-30 06:57

I\'m using ORMLite in an android project, and I\'m not wanting to use the extended activities because I\'m inserting values into the database on an AsyncTask.

In the

2条回答
  •  南笙
    南笙 (楼主)
    2020-12-30 07:23

    I'm using ORMLite in an android project, and I'm not wanting to use the extended activities because I'm inserting values into the database on an AsyncTask.

    You are on the right track but a little off @Matt. Frankly I'd never done a project without extending our base classes. But it is a good exercise so I've created this ORMLite example project which uses an Activity and manages its own helper.

    Your DBHelper class is fine but really you do not need your DataAccess class. In each of your activities (or services...) you will need to have something like the following:

    private DBHelper dbHelper = null;
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (dbHelper != null) {
            OpenHelperManager.releaseHelper();
            dbHelper = null;
        }
    }
    
    private DBHelper getHelper() {
        if (dbHelper == null) {
            dbHelper = (DBHelper)OpenHelperManager.getHelper(this, DBHelper.class);
        }
        return dbHelper;
    }
    

    You [obviously], then use this in your code by doing something like:

    Dao someObjectDao = getHelper().getSomeObjectDao();
    

    So whenever you call getHelper() the first time, it will get the helper through the manager, establishing the connection to the database. Whenever your application gets destroyed by the OS, it will release the helper -- possibly closing the underlying database connection if it is the last release.

    Notice that the OpenHelperManager.getHelper() needs the Context as the first argument in case you do this without even an Activity base class.

    Edit:

    If you do want to create a DataAccess type class to centralize the handling of the helper class then you will need to make the methods static and do your own usage counter. If there are multiple activities and background tasks calling getHelper() then the question is when do you call releaseHelper()? You'll have to increment a count for each get and only call release when the counter gets back to 0. But even then, I'm not 100% sure how many lines you'd save out of your activity class.

提交回复
热议问题