Android - 如何在整个应用程序生命周期中使用ORMLite dbhelper

时间:2014-07-18 13:38:41

标签: android database helper ormlite android-context

我想使用ORMLite,但我不喜欢为每项活动管理1个数据库助手。在整个应用程序生命周期中拥有一个更好吗?到目前为止,我已经使用了greendao并且没有这个问题。

我想实现它,但是我无法找到任何合适的方法来在销毁app时正确地释放db helper(我可以在Application' onCreate中轻松打开它),因为没有Application&#39 ; s onDestroy()方法。

有没有人有办法做到这一点?

2 个答案:

答案 0 :(得分:1)

OrmliteOrmLiteBaseActivity,它可以自行管理与活动周期的连接。您的所有活动都应扩展此类,您无需关心何时销毁连接。您可以多次调用帮助程序,连接将被释放  每个活动的onDestroy()方法。

如果您的活动不是基础Android活动,例如SherlockActivityActionBarActivity,您可以考虑从OrmLiteBaseActivity复制代码并制作自己的基本活动,然后对其进行扩展。

这就是我在许多应用程序中所做的,我没有看到任何问题。希望这可以帮助!
P / s:您甚至可以使用OrmLiteBaseService

为Android服务做同样的事情

答案 1 :(得分:0)

您可以使用Singleton模式:

package com.example.stackoverflowsandbox;

public class MySingletonHelper extends OrmLiteSqliteOpenHelper {
    private static MySingletonHelper instance;

    public static MySingletonHelper getInstance() {
        if ( MySingletonHelper.instance == null ) {
            MySingletonHelper.instance = new MySingletonHelper();
        }

        return MySingletonHelper.instance;
    }

    private MySingletonHelper() {
        // code here...
    }

    @Override
    public void onCreate( SQLiteDatabase arg0, ConnectionSource arg1 ) {
        // code here...
    }

    @Override
    public void onUpgrade( SQLiteDatabase arg0, ConnectionSource arg1, int arg2, int arg3 ) {
        // code here...
    }
}

在此处查看更多内容:http://en.wikipedia.org/wiki/Singleton_pattern