Android系统会自动关闭一个开放的SQLite数据库吗?我已经实现了一个用于访问数据的单例类,有时需要在工作线程上运行那些方法。我有一个同步功能与在后台运行的查询,这是代码:
public ArrayList<ActualCall> getUnsentCalls(boolean forUnsentSignature) {
ArrayList<ActualCall> calls = new ArrayList<ActualCall>();
Cursor c;
open();
if (forUnsentSignature)
c = db.rawQuery("SELECT * FROM " + TXN_ACTUAL_CALL_COMPONENT
+ " WHERE sentFlag=1 and sigSentFlag=?", new String[] {"0"});
else
c = db.rawQuery("SELECT * FROM " + TXN_ACTUAL_CALL_COMPONENT
+ " WHERE sentFlag=? AND signature != ''", new String[] {"0"});
if (c.moveToFirst()) {
do {
if (!db.isOpen())
open();
ActualCall call = new ActualCall();
call.setAcpComponentId(c.getString(c.getColumnIndex("acpComponentId")));
call.setAcpDate(c.getString(c.getColumnIndex("acpDate")));
call.setAcpId(c.getString(c.getColumnIndex("acpId")));
call.setCallEndTime(c.getString(c.getColumnIndex("callEndTime")));
call.setCallStartTime(c.getString(c.getColumnIndex("callStartTime")));
call.setCoordinates(c.getString(c.getColumnIndex("coordinates")));
call.setDeviceTimestamp(c.getString(c.getColumnIndex("deviceTimestamp")));
call.setDoctorId(c.getString(c.getColumnIndex("doctorId")));
call.setSignature(c.getString(c.getColumnIndex("signature")));
call.setSigSentFlag(c.getString(c.getColumnIndex("sigSentFlag")));
call.setTimeSpent(c.getString(c.getColumnIndex("timeSpent")));
call.setSentFlag(c.getString(c.getColumnIndex("sentFlag")));
call.setCoordinates(c.getString(c.getColumnIndex("coordinates")));
calls.add(call);
} while (c.moveToNext());
}
c.close();
db.close();
return calls;
}
正如你所看到的,我已经在初始行上调用了open()但是我收到的错误告诉我的数据库已经关闭了。这是堆栈跟踪:
java.lang.IllegalStateException: database
/data/data/com.***.****/databases/****.db (conn# 0) already closed
at android.database.sqlite.SQLiteDatabase.verifyDbIsOpen(SQLiteDatabase.java:2123)
at android.database.sqlite.SQLiteDatabase.lock(SQLiteDatabase.java:398)
at android.database.sqlite.SQLiteDatabase.lock(SQLiteDatabase.java:390)
at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:74)
at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:311)
at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:292)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:156)
at android.database.AbstractCursor.moveToFirst(AbstractCursor.java:233)
at com.***.****.datalayer.ESCAndroidDataLayer.getUnsentCalls(ESCAndroidDataLayer.java:5340)
at com.***.****.synchall.SynchAll$UnsentSignatureSender.run(SynchAll.java:1750)
同样,如果有帮助的话,在Thread类上调用上面的方法。我发现有关SQLite自动关闭的链接,但我不理解他的解决方案:http://darutk-oboegaki.blogspot.com/2011/03/sqlitedatabase-is-closed-automatically.html
答案 0 :(得分:0)
尝试在c.moveToFirst()之前调用 db.acquireReference()
db.acquireReference();
if (c.moveToFirst()) {
或者仅仅通过“ if(db.isOpen())”将db.close()括起来就足够了。
if (db.isOpen())
{
db.close();
}
我不太确定,但这会改变一些事情。