我正在开发一个 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();
}
}
}
最佳答案
如果您发现自己使用来自不同进程的 SQL 数据库,您真的应该考虑将其封装在内容提供程序中。与加载程序一起,内容提供程序促进跨进程、DataObservers 等的访问。甚至还有用于创建它们的 API 指南:Creating a Content Provider
关于android - 数据库无法连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15280294/