Where to close SQLiteOpenHelper if I use singleelton one

I have the following class that allows the user to get an object SQLiteOpenHelper

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();
    }

}

I want to know where I should closepass this singleton object, I can not pass by the method onTerminate(), since it will not be called. I want to close it when the user exits my application? any solution for this

+3
source share
3 answers

" " Android . Activity, , Activity , - , , , .

, Application getDBHelper(), Activity, .

+3

I suggest using AtomicIntegerto track the number of calls getDBHelper. Then you can call getDBHelperin each Activityand close onPause/ onDestroy(which suits you). Each closed call decreases the counter, and if the counter is in 0, you can really close your assistant. For example, see this sample code from ORMlite, which demonstrates this approach.

0
source

All Articles