android開發資料庫Cursor 錯誤android.database.CursorWindowAllocationException

來源:互聯網
上載者:User

android開發資料庫Cursor 錯誤android.database.CursorWindowAllocationException

做android 開發的經常會遇android.database.CursorWindowAllocationException這樣子的錯誤;一般出現這樣的錯誤,大部分原因是因為沒有關閉cursor,或者是因為Cursor使用不當,之前我的遇到這樣的代碼:

 ForecastData situation = null;    ................    Cursor cursor = mContext.getContentResolver().query(WEATHER_URI, null,    null, null, null);    try {        if (cursor != null && cursor.moveToFirst()) {        ...........        cursor.close();        }   } catch (Exception e) {        e.printStackTrace();   } finally {        if (cursor != null) {        cursor.close();   }}return situation;}
初看一下沒有什麼問題,但如果Cursor cursor = mContext.getContentResolver().query這裡返回的錯誤還是會有可能造成程式的未關閉Cursor,因此我們改成標準寫法:

Cursor cursor = null;try {cursor = getContentResolver().query(URI, .....);// 1        //dosomething} finally {if (cursor != null) {cursor.close();// 2}}
這樣改了之後,運行了很多個版本都一直沒有問題。直到有一天一個同事發現可能查詢資料庫比較耗時。因此把方法放到線程裡面去執行,而已每次查詢的時候都會建立一個線程。沒有想到上面代碼又出錯誤了,如果您稍不留意不會懷疑這塊代碼的問題,因為try-finally寫法不存在邏輯上的問題。由於這裡未考慮到多線程情境,try-finally並不能保證query開啟遊標在dosomething時,被其他線程再次調用query開啟遊標。所以當遇到存在多線程的調用時必須對遊標開啟到關閉時間段添加鎖,即這裡是對try-finally塊加鎖。

下面簡單解釋一下:

假設:線程A執行到1處建立了一個Cursor,然後dosomething比較耗時........

線程B又來查詢資料庫,因此到1處又建立一個Cursor,此時如果AB執行完,就會關閉鎖,看起來沒有問題,但由於是同一個對象,所以AB關閉的cursor都是B建立的,因此
A建立的Cursor就沒有關閉!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.