我有一个非常奇怪的问题,我无法在模拟器或任何经过测试的Android设备上重现。
我有一个SQlite数据库控制器,它包含所有我的数据访问功能,在这个类中我有一个简单的函数来检查表是否存在:
public boolean tableExists(String tableName) {
if(db==null || !db.isOpen()) db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
cursor.close();
}
return false;
}
在我的应用程序启动时,我创建一个异步任务来检查更新,在此过程中,我将检查数据库中是否存在本地表。
抛出的错误是在Cursor cursor = db.rawQuery(...行,错误是:
java.lang.IllegalStateException:database ... db.sqlite已关闭
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:200)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
at java.lang.Thread.run(Thread.java:1019)
Caused by: java.lang.IllegalStateException: database /data/data/com.xxx.xxx.xxx.android/databases/db.sqlite already closed
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:59)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1364)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1332)
at com.xxx.xxx.xxx.utils.SQLiteController.tableExists(SQLiteController.java:1463)
我无法重现此错误,但根据ACRA,这种情况会在不同设备中多次发生。
有人可以告诉我这个吗?
感谢。
答案 0 :(得分:0)
请将第二个cursor.close();
放在else块后面
public boolean tableExists(String tableName) {
if(db==null || !db.isOpen()) db = dbhelper.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='"+tableName+"'", null);
if(cursor!=null) {
if(cursor.getCount()>0) {
cursor.close();
return true;
}
else{
cursor.close();
}
}
return false;
}