其中,如果我使用的是singelton一个关闭SQLiteOpenHelper [英] Where to close the SQLiteOpenHelper if i am using a singelton one

查看:97
本文介绍了其中,如果我使用的是singelton一个关闭SQLiteOpenHelper的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下类,允许用户获得 SQLiteOpenHelper 对象

i have the following class that permit user to get a SQLiteOpenHelper object

import android.content.Context;

public class DBUtils {  

    private DBUtils(){

    }


    private static DBHelper dbHelper ;


    public static synchronized DBHelper getDBHelper(Context context){

        if(dbHelper == null){
            dbHelper = new DBHelper(context, ApplicationMetaData.DATABASE_NAME, null, ApplicationMetaData.DATABASE_VERSION);
        }
        return dbHelper;


    }



    public static synchronized void closeDBHelper(){

        if(dbHelper!=null )
            dbHelper.close();
        dbHelper = null;
    }


    @Override
    protected Object clone() throws CloneNotSupportedException {
        // TODO Auto-generated method stub
        throw new CloneNotSupportedException();
    }

}

我想知道我应该在哪里关闭此singleton对象我不能中继 onTerminate()法,因为它不会被调用。我想关闭它,当用户退出我的应用程序?此解决方案的任何

i want to know where should i close this singleton object i can't relay on the onTerminate() method since it will not be called . i want to close it when the user exit my app ? any solution for this

推荐答案

由于没有这样的应用程序被关闭事件在Android的设计。你要么必须处理您为每个活动的数据库连接,所以当你的活动被破坏,你就会知道,或者你必须以某种方式照顾哪些对象使用的数据库帮助,只有在没有其他对象是使用辅助更多关闭帮手。

As there is no such "app is closed" event in Android by design. You either have to handle you database connection per Activity so you will know when you Activity gets destroyed or you have to somehow take care about which object uses the database helper and only close the helper when no other object is using the helper any more.

如果你留在单身的解决方案要知道一个应用程序上下文传递到getDBHelper()方法,而不是一个Activity上下文因为这可能会导致内存泄漏。

If you stay with the singleton solution be aware to pass an Application context to the getDBHelper() method and not a Activity context as this might lead to memory leaks.

这篇关于其中,如果我使用的是singelton一个关闭SQLiteOpenHelper的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆