Skip to content

Instantly share code, notes, and snippets.

@nonom
Created May 3, 2014 12:01
Show Gist options
  • Save nonom/8d5bf3637d1902188b49 to your computer and use it in GitHub Desktop.
Save nonom/8d5bf3637d1902188b49 to your computer and use it in GitHub Desktop.
package com.nonomartinez.app.managers;
import java.util.concurrent.atomic.AtomicInteger;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* Database Manager
*
* @author nonom
*/
public class DatabaseManager
{
private final AtomicInteger _counter = new AtomicInteger();
private static DatabaseManager _instance;
private static SQLiteOpenHelper _helper;
private SQLiteDatabase _db;
public static synchronized void initialize(SQLiteOpenHelper helper)
{
if (_instance == null) {
_instance = new DatabaseManager();
_helper = helper;
}
}
public static synchronized DatabaseManager getInstance()
{
if (_instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() + " initialize() first.");
}
return _instance;
}
public synchronized SQLiteDatabase openDatabase()
{
if (_counter.incrementAndGet() == 1) {
_db = _helper.getWritableDatabase();
}
return _db;
}
public synchronized void closeDatabase()
{
if (_counter.decrementAndGet() == 0) {
_db.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment