jamalM
jamalM

Reputation: 57

Understanding SQlite close()

I created a SQlite DB. It is no problem to write or read from my DB. In my DBHandler.class I added some methods to read one column for example. Every method has dbHandler.close() line. If I want to call a method from the DBHandler.class, so I have to make something like: ... DBHandler db = new DBHandler(this); ... list = db.getAllBlock()

Shoud I put the line db.close() after list... ????? That is my problem to understand.... Thank you!

Upvotes: 0

Views: 153

Answers (1)

Lojko
Lojko

Reputation: 173

It's inefficient to constantly have to reconnect to the database everytime you want to do something, so remove the close() statements from each line and create a single instance of the DB Handler class:

It's much better to have a single DBHandler

DBHandler db;

public Activity/Class Constructor()
{
     DBHandler db = new DBHandler(this);
}

private void DoSomethingWithDatabase()
{
   db.doSomethingHere();
}

private void DoSomethingWithDatabaseAgain()
{
   db.doSomethingThere();
}

public void Activity/ClassClose()
{
    db.CloseDatabase();
}

instance inside which ever Activity/Class is using it, then have a close method in DBHandler, which closes the connection to the database after the activity/class is finished using it.

public class DBHandler
{  
    private static SQLiteDatabase m_DB;

    public DBHandler open() throws android.database.SQLException
    {
        m_DB = m_DBHelper.getWritableDatabase();
    }

    public void doSomethingHere()
    {
       m_DB.getAllBlock()
    }

    public void doSomethingThere()
    {
       m_DB.getAllSomethingElse()
    }

    public void CloseDatabase()
    {
       m_DB.close();
    }
}

In fact, it's even better to have the DBHandler as a Singleton then you can have app wide database access without the inefficient overheads of re-establishing connections every time you want it.

Upvotes: 1

Related Questions