查詢資料會比較耗時,所以我們想把查詢資料放在一個非同步任務中,查詢結果獲得Cursor,然後在onPostExecute (Cursor result)方法中設定Adapter,我們可能會想到使用Activity的managedQuery來產生Cursor,這樣Cursor就會與Acitivity的生命週期一致了,多麼完美的解決方案!然而事實上managedQuery也有很大的局限性,managedQuery產生的Cursor必須確保不會被替換,因為可能很多程式事實上查詢條件都是不確定的,因此我們經常會用新查詢的Cursor來替換掉原先的Cursor。因此這種方法適用範圍也是很小。
我們不能直接將Cursor關閉掉,但是注意,CursorAdapter在Acivity結束時並沒有自動的將Cursor關閉掉,因此,你需要在onDestroy函數中,手動關閉。
複製代碼 代碼如下:
@Override
protected void onDestroy() {
super.onDestroy();
mPhotoLoader.stop();
if(mAdapter != null && mAdapter.getCursor() != null) {
mAdapter.getCursor().close();
}
}
如果沒有在Adapter中用到Cursor,可以手動關閉Cursor。
複製代碼 代碼如下:
Cursor cursor = null;
try{
cursor = mContext.getContentResolver().query(uri,null,null,null,null);
if(cursor != null){
cursor.moveToFirst();
//do something
}
}catch(Exception e){
e.printStatckTrace();
}finally{
if(cursor != null){
cursor.close();
}
}