我有一个列表视图。我从 SQLite 数据库获取数据。我收到此错误:
当我从第 20 行转到第 21 行时,就会出现这种情况:
我将
cursor.deactivate()
和cursor.close()
放在第50行,但没有结果。为什么我会收到此错误以及如何解决它?
您必须在数据库之前关闭游标。将代码放入
try
/ catch
块和 finally
块中,关闭光标,然后关闭数据库:
try {
db = ...
} catch(Exception ex) {
// Log the exception's message or whatever you like
} finally {
try {
if( cursor != null && !cursor.isClosed())
cursor.close();
if( db.isOpen() )
db.close();
} catch(Exception ex) {}
}
在使用 DB 或 Content Provider 进行 IO 时,关闭顺序非常重要。 欲了解更多信息,请参阅此链接
要发现此类问题,只需为调试版本启用 StrictMode,如下所示:
public void onCreate() {
if (DEVELOPER_MODE) {
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.detectDiskReads()
.detectDiskWrites()
.detectNetwork() // or .detectAll() for all detectable problems
.penaltyLog()
.build());
StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
.detectLeakedSqlLiteObjects()
.detectLeakedClosableObjects()
.penaltyLog()
.penaltyDeath()
.build());
}
super.onCreate();
}
更多信息@ http://developer.android.com/reference/android/os/StrictMode.html
祝一切顺利,
始终记得在关闭数据库之前通过调用cursor.close()来关闭游标。这应该可以解决你的问题。
让 Activity 使用
startManagingCursor(c)
管理光标生命周期就可以了。
我建议您访问Getnewapks