android turns off Cursor's code methods in asynchronous tasks

  • 2020-05-19 05:52:39
  • OfStack

Querying data is time-consuming, so we want to put the querying data in an asynchronous task, get Cursor as the result of the query, and then set Adapter in onPostExecute (Cursor result) method. We may think of using Activity managedQuery to generate Cursor, so Cursor will correspond to Acitivity's lifecycle 1. What a perfect solution! However, in fact, managedQuery also has great limitations. Cursor generated by managedQuery must be ensured that it will not be replaced, because many programs may actually have uncertain query conditions, so we often replace the original Cursor with Cursor of the new query. So the scope of this method is very small.

We cannot turn Cursor off directly, but notice that CursorAdapter does not turn Cursor off automatically at the end of Acivity, so you need to turn Cursor off manually in the onDestroy function.


@Override
    protected void onDestroy() {
        super.onDestroy();
        mPhotoLoader.stop();
        if(mAdapter != null && mAdapter.getCursor() != null) {
            mAdapter.getCursor().close();
        }
    }

If Cursor is not used in Adapter, you can manually close 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();
    }
}


Related articles: