Search code examples
androidcursorandroid-cursoradapter

Android: Where close cursor using CustomAdaters in AsynTask


I have a big problem.. This is the code:

private class ViewDataTableTask extends AsyncTask<Void, Void, String> {
    ...

    protected String doInBackground(Void... params) {

        Cursor listCursor = db.rawQuery("SELECT ..." , null);
        ListView table_body = new ListView(context);

        try{
            table_body.setAdapter(new MyAdapter(context , listCursor));
        }finally{
             if(listCursor != null){
             listCursor.close();
        }
        ...
   }
   ...
}

MyAdapter is a custom CursorAdapter that uses the getView() and newView() method

If i run the previous code i get the following error:

java.lang.IllegalStateException: attempt to re-open 
an already-closed object: android.database.sqlite.SQLiteQuery

It seems that getView() and newView() method run on UI Thread!!!!!!

The question is simple: where have i to put cursor.close()? I don't want to use CursorLoader and/or startManagingCursor(..)

Please help me!!!


Solution

  • The got Cursor instance will be used by CursorAdapter for as long as user uses your listView. That's why you should not close the cursor so early. Whenever your instance of Activity is about to be destroyed it is time to close that cursor. Or whenever you change the cursor (if this is a case for your app) for that CursorAdapter, close the previously used.

    And as others say reset the cursor to CursorAdapter on the UI thread (in AsyncTask.onPostExecute()).