我试图弄清楚为什么我偶尔会收到 IllegalStateException。我找不到任何好的示例来展示如何使用线程加载列表来查询 SQLite 数据库。我在下面包含了我的代码。大多数时候它工作正常,但偶尔我会收到 IllegalStateException。
我在我的另一个活动(即 ExpandableListActivity 的实例)中也遇到了类似的异常。该异常指出“尝试重新查询已经关闭的游标”。
有人可以告诉我执行此操作的正确方法,以免导致任何错误吗?我更愿意使用游标而不是将所有数据复制到内存中。如果我无法弄清楚这一点,那么我将不得不将其全部加载到内存中。
我认为这个问题与 startManagingCursor(Cursor) 以及数据库连接在 onDestroy() 中关闭的事实有关。
请帮忙
-- tale
public class MyListActivity extends ListActivity {
private MyCursorAdapter adapter;
private SQLiteDatabase db = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
new RetrieveCursorTask(this).execute((Void[]) null);
} catch (Exception e) {
}
}
@Override
protected void onDestroy() {
super.onDestroy();
// Null out the cursor.
if (adapter != null) {
adapter.changeCursor(null);
adapter = null;
}
if (db != null && db.isOpen()) {
db.close();
}
}
private class RetrieveCursorTask extends AsyncTask<Void, Void, Cursor> {
private Context ctx;
public RetrieveCursorTask(Context ctx) {
this.ctx = ctx;
}
@Override
protected Cursor doInBackground(Void... params) {
Cursor cursor = null;
DbHelper helper = new DbHelper(ctx);
try {
db = helper.getReadableDatabase();
cursor = db.query("users",
new String[] {
DbHelper.ID_COLUMN,
DbHelper.UID_COLUMN
},
null, null, null, null, null);
startManagingCursor(cursor);
} catch (Exception e) {
}
return cursor;
}
@Override
protected void onPostExecute(Cursor cursor) {
super.onPostExecute(cursor);
if (cursor != null) {
try {
adapter = new MyCursorAdapter(ctx, cursor);
} catch (Exception e) {
}
setListAdapter(adapter);
}
}
}
private class MyCursorAdapter extends CursorAdapter {
private Context ctx;
public MyCursorAdapter(Context context, Cursor c) {
super(context, c);
this.ctx = context;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// ...
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// ...
}
}
}