Will Kru
Will Kru

Reputation: 5212

Android database connection best practice

What is considered to be best practice for handling database connections? (I omitted the constructor and onUpgrade method within the DatabaseHelper class) These are just 2 ways I found on the internet, perhaps you have a better way of handling? I would love to hear.

Option 1

public class DatabaseManager {

private SQLiteDatabase mDb;

public DatabaseManager(Context context) {

   DatabaseHelper helper = new DatabaseHelper(context);
   helper.getWritableDatabase();
}

// ... methods that use mDb

private class DatabaseHelper extends SQLiteOpenHelper {

   @Override
   public void onCreate(SQLiteDatabase db) {

      mDb = db;
      //create database
   }

   @Override
   public void onOpen(SQLiteDatabase db) {

      mDb = db;
   }
}

}

Option 2

public class DatabaseManager {

private DatabaseHelper mDbHelper;

public DatabaseManager(Context context) {

   mDbHelper = new DatabaseHelper(context);
}

// ... methods that fetch the db

private void sampleMethod() {
   SQLiteDatabase db = mDbHelper.getWritableDatabase();
   //do stuff with database
   mDbHelper.close();
}

private static class DatabaseHelper extends SQLiteOpenHelper {

   @Override
   public void onCreate(SQLiteDatabase db) {

      //create database
   }
}

}

Also, is it needed to call close() everytime you used the database within option 2? As for using option 1, I guess you need to call close() when the app's onDestroy is called?

Upvotes: 2

Views: 1911

Answers (1)

Mullins
Mullins

Reputation: 2364

I used to worry about all this but recently I started using ORMLite. It is a very light ORM with Android libraries and saves you worrying about this kind of stuff.

I would say that this could very soon become best practice as it removes a lot of repeated code when dealing with databases. It is also being updated regularly and the maintainer responds to queries very quickly.

Upvotes: 1

Related Questions