我正在开发一个Android应用程序,它使用来自不同线程和进程的sqlite数据库,例如Widget和服务。
使用单例模式授予连接,我随机收到此错误:应用程序仍然卡在getWriteableDatabase()
方法中,此警告显示在日志中
W/SQLiteConnectionPool( 2021): The connection pool for database '/data/data/xyz' has been unable to grant a connection to thread xyz (xyz) with flags 0x1 for xyz seconds.
W/SQLiteConnectionPool( 2021): Connections: 0 active, 1 idle, 0 available.
此错误通常在应用程序关闭几个小时后发生,我重新打开它,但没有正式的方法来重现此错误。
我尝试使用这两种方法,但没有幸运:
class DB extends SQLiteOpenHelper {
DB databaseHelper;
SQLiteDatabase database;
/**
* Open a Database Helper.
*
* @param c the Context used to open the Database.
* @return the Database Helper.
*/
public static DB getInstance(final Context c) {
if (databaseHelper == null) {
databaseHelper = new DB(c.getApplicationContext());
}
return databaseHelper;
}
int active_connections;
/**
* @return the Database connection to use
* @see closeReadableDataBase()
*/
public synchronized SQLiteDatabase getDatabase() {
if (database == null || !database.isOpen()) {
if(database!=null) database.close();
database = getWritableDatabase();
active_connections=0;
database.setLockingEnabled(false);
TransitionHelper.execSQL(database, "PRAGMA read_uncommitted = true;");
TransitionHelper.execSQL(database, "PRAGMA synchronous=OFF;");
}
active_connections++;
return database;
}
/**
* Closes the database connection.
* @see openDatabaseForRead()
*/
public synchronized void closeDatabase() {
active_connections--;
if(active_connections==0 && database!=null){
database.close();
database=null;
}
}
}
和
class DB extends SQLiteOpenHelper {
DB databaseHelper;
SQLiteDatabase database;
public static DB getInstance(final Context c) {
if (databaseHelper == null) {
databaseHelper = new DB(c.getApplicationContext());
}
return databaseHelper;
}
public synchronized SQLiteDatabase getDatabase() {
if (database == null || !database.isOpen()) {
if(database!=null) database.close();
database = getWritableDatabase();
}
return database;
}
public synchronized void closeDatabase() {
if(database!=null){
database.close();
}
}
}
答案 0 :(得分:1)
如果您发现自己使用来自不同进程的SQL数据库,则应该考虑将其封装在内容提供程序中。与加载器结合使用,内容提供者便于跨进程,DataObservers等进行访问。甚至还有一个用于创建它们的API指南:Creating a Content Provider