Created
May 3, 2014 12:01
-
-
Save nonom/8d5bf3637d1902188b49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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