MyDatabaseHelper helper = new MyDatabaseHelper(this);
SQLiteDatabase database = helper.getReadableDatabase();
String[] columns = {
"_ID",
"Title",
"Subtitle"
};
Cursor cursor = database.query("MyTable", columns, null, null, null, null, null);
// Notice the position of these 2 lines. Will NOT crash if I move them to the bottom.
database.close();
helper.close();
String[] fromColumns = {
"Title",
"Subtitle"
};
int[] toViews = {
R.id.list_view_item_text_view_title,
R.id.list_view_item_text_view_subtitle
};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.list_view_item, cursor, fromColumns, toViews, 0);
ListView listView = (ListView) findViewById(R.id.activity_release_list_view);
// Crashed!
listView.setAdapter(adapter);
/**
* Caused by: java.lang.IllegalStateException: Cannot perform this operation because the connection pool has been closed.
* at android.database.sqlite.SQLiteConnectionPool.throwIfClosedLocked(SQLiteConnectionPool.java:962)
* at android.database.sqlite.SQLiteConnectionPool.waitForConnection(SQLiteConnectionPool.java:599)
* at android.database.sqlite.SQLiteConnectionPool.acquireConnection(SQLiteConnectionPool.java:348)
* at android.database.sqlite.SQLiteSession.acquireConnection(SQLiteSession.java:894)
* at android.database.sqlite.SQLiteSession.executeForCursorWindow(SQLiteSession.java:834)
* at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:62)
* at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:143)
* at android.database.sqlite.SQLiteCursor.getCount(SQLiteCursor.java:133)
* at android.support.v4.widget.CursorAdapter.getCount(CursorAdapter.java:202)
* at android.widget.ListView.setAdapter(ListView.java:460)
*/
仅当我在listView.setAdapter(adapter)
之后关闭数据库和数据库帮助程序时才有效。我关闭了数据库,因为我已经在Cursor
中得到了结果集。 Cursor
需要SimpleCursorAdapter
,ListView
需要{{1}}。它仍然崩溃。无论如何,ListView与数据库有什么关系?
答案 0 :(得分:0)
适配器正在进行生命查询;它不能使用封闭的查询。
ListView从适配器读取足够的行以填充屏幕。只有在用户向下滚动后,ListView才会向适配器询问更多行。所以这意味着当发生这种情况时,查询仍然必须处于活动状态。
实质上,这意味着在关闭显示ListView的活动之前不要关闭数据库。