//忘记原作者连接,请见谅。
public class DatabaseManager {
private static DatabaseManager instance;
private static SQLiteOpenHelper mDatabaseHelper;
private SQLiteDatabase mDatabase;
//初始化
public static synchronized void initializeInstance(SQLiteOpenHelper helper) {
if (instance == null) {
synchronized (DatabaseManager.class) {
if (null == instance) {
instance = new DatabaseManager();
mDatabaseHelper = helper;
}
}
}
}
public static synchronized DatabaseManager getInstance() {
if (instance == null) {
throw new IllegalStateException(DatabaseManager.class.getSimpleName() +
" is not initialized, call initializeInstance(..) method first.");
}
return instance;
}
//写
public synchronized SQLiteDatabase openWritableDatabase() {
if(mOpenCounter.incrementAndGet() == 1) {
mDatabase = mDatabaseHelper.getWritableDatabase();
}
return mDatabase;
}
//读
public synchronized SQLiteDatabase getReadableDatabase() {if(mOpenCounter.incrementAndGet() == 1) {
// Opening new database
mDatabase = mDatabaseHelper.getReadableDatabase();
}
return mDatabase;
}
//同步关闭
public synchronized void close() {
if(mOpenCounter.decrementAndGet() == 0) {
mDatabase.close();
}
}
//强制真正的关闭
public synchronized void trueClose() {
mDatabase.close();
}
}
用法:在myapplication调用初始化:
DatabaseManager.initializeInstance(new DBHelper(this));