Releasing ORMLite helper on @Singleton

大城市里の小女人 提交于 2019-12-07 07:23:51

问题


I have a @Singleton class where I've injected an instance of OrmLiteSqliteOpenHelper. Do I actually ever need to call the OpenHelperManager.releaseHelper()? In case I do, where and how should it be done as the class doesn't extend any Android base class where I could get to the onDestroy?


回答1:


There is an ORMLite example Android project which demonstrates this called HelloAndroidNoBase. I'd check it out.

The relevant code section from the main Activity is included below. You'll need to have this sort of code in each one of your Activity or other classes that uses the database.

If your class does not have an onDestroy() method then you need to add one and call it from one of the other classes that does have onDestroy(). The main Activity is a good place for this. So your MainActivity.onDestroy() would call yourClass.onDestroy() when the application is shutting down.

public class HelloNoBase extends Activity {

    private DatabaseHelper databaseHelper = null;

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

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


来源:https://stackoverflow.com/questions/12068634/releasing-ormlite-helper-on-singleton

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!