Best place to close database connection

I was looking for a while for answer on my question but I didn`t get what I need. I have an application with a ListView, and form where I can add new record to DB. So there is not much queries to do.

How to handle connections to db ? Should I close it after getting what I want or should I keep it open whole time until app is closed ? I want to know what is the best way while thinking about performence and battery life.


Solution 1:

According to this post by a Google engineer (Dianne Hackborn), there's nothing wrong with leaving the database connection open:

Android made a deliberate design decision that is can seem surprising, to just give up on the whole idea of applications cleanly exiting and instead let the kernel clean up their resources. After all, the kernel needs to be able to do this anyway. Given that design, keeping anything open for the entire duration of a process's life and never closing it is simply not a leak. It will be cleaned up when the process is cleaned up.

So, for simplicity, I would extend the Application class to provide a single well-defined entry point for your code, and open the database connection in its onCreate(). Store the DB connection as a field in your Application, and provide an accessor method to make the connection available to rest of your code.

Then, don't worry about closing it.

Solution 2:

In general I'd close the connection in the onDestroy() function of the Activity which opened the connection. I'd close() a cursor from a database in the function which uses the cursor.

public MyActivity extends Activity{
    private myDatabase mDatabase; // myDatabase extends SQLiteOpenHelper
    private Cursor mCursor;

    public MyActivity(Context context){
        super(context);
        initMemberVariables();
    }

    public ElementButton(Context context, AttributeSet attrS){
    super(context, attrS);
        initMemberVariables();
    }

    public ElementButton(Context context, AttributeSet attrS, int defStyle){
        super(context, attrS, defStyle);
        initMemberVariables();
    }

    private void initMemberVariables(){
        mDatabase = new PSEdb(this.getContext());
    }

    private void getData(){
        mCursor = mDatabase.MyGetterFunction();
        while(mCursor.moveToNext()){
            try{
                // populate your data
            }catch(CursorIndexOutOfBoundsException ex){
                // handle the exception
            }
        }
        mCursor.close();
    }

    @Override
    public void onDestroy(){
        super.onDestroy();
        mDatabase.close();
    }
}

Solution 3:

Establishing the connection to the database is expensive. If connections are not in short supply, and the database is local, I'd keep the connection open rather than establishing it for each write operation to the database, as you'd typically do in a client-server application that needs to scale to accommodate a large number of concurrent users.