android在非同步任務中關閉Cursor的代碼方法_Android

來源:互聯網
上載者:User

查詢資料會比較耗時,所以我們想把查詢資料放在一個非同步任務中,查詢結果獲得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();
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.