6

One of the benefits I thought of using CursorLoaders and Loadermanagers was that you didn't need to manually manage the lifecycle of the cursor. So I used a loadermanager to bind an adapter to an AutoCompleteTextView using the support package.

It works quite well except that it randomly throws an error saying "IllegalStateException - attempt to re-open an already closed object". Surely that's not supposed to happen if we're using the loader manager?

Here's the code:

package com.bhagwad.tennis;

import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v4.widget.SimpleCursorAdapter.CursorToStringConverter;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AutoCompleteTextView;
import android.widget.Button;

import com.bhagwad.tennis.TennisSchedule.TennisScheduleColumns;


public class WidgetConfiguration extends FragmentActivity implements OnClickListener, LoaderCallbacks<Cursor> {

    Button mSaveWidget;
    AutoCompleteTextView mPlayerName;
    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    String mSelection ="";
    SimpleCursorAdapter mAdapter;

    public static String PREFS = "com.bhagwad.tennis.appwidget";
    public static final String PREFS_PREFIX_KEY = "prefix_";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.widget_configuration);

        mPlayerName = (AutoCompleteTextView) findViewById(R.id.edit_filter);

        mPlayerName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (!s.equals(""))
                    mSelection = s.toString();
                else
                    mSelection = "";

                getSupportLoaderManager().restartLoader(0, null, WidgetConfiguration.this);



            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // TODO Auto-generated method stub

            }
        });

        // Set up the adapter

        mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null, new String[] {TennisScheduleColumns.PLAYER_NAME}, new int[] {android.R.id.text1}, 0);
        mAdapter.setCursorToStringConverter(new CursorToStringConverter() {

            @Override
            public CharSequence convertToString(Cursor c) {

                return c.getString(c.getColumnIndexOrThrow(TennisScheduleColumns.PLAYER_NAME)); 

            }
        });

        mPlayerName.setAdapter(mAdapter);

        getSupportLoaderManager().initLoader(0, null, this);

    }


    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {

        return new CursorLoader(this, TennisScheduleColumns.CONTENT_URI_PLAYERS, new String[] {TennisScheduleColumns._ID, TennisScheduleColumns.PLAYER_NAME}, TennisScheduleColumns.PLAYER_NAME + " LIKE ?", new String[] {"%"+mSelection+"%"}, null);

    }


    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        mAdapter.swapCursor(null);

    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        mAdapter.swapCursor(data);


    }


}

Here's the error stack:

08-16 22:21:23.244: E/AndroidRuntime(25475): java.lang.IllegalStateException: attempt to re-open an already-closed object: android.database.sqlite.SQLiteQuery (mSql = SELECT _id, player_name FROM players WHERE (player_name LIKE ?)) 
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.sqlite.SQLiteClosable.acquireReference(SQLiteClosable.java:33)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.sqlite.SQLiteQuery.fillWindow(SQLiteQuery.java:82)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.sqlite.SQLiteCursor.fillWindow(SQLiteCursor.java:164)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.sqlite.SQLiteCursor.onMove(SQLiteCursor.java:147)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:178)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.database.CursorWrapper.moveToPosition(CursorWrapper.java:162)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.support.v4.widget.CursorAdapter.getItem(CursorAdapter.java:213)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.widget.AutoCompleteTextView.buildImeCompletions(AutoCompleteTextView.java:1113)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.widget.AutoCompleteTextView.showDropDown(AutoCompleteTextView.java:1072)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.widget.AutoCompleteTextView.updateDropDownForFilter(AutoCompleteTextView.java:950)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.widget.AutoCompleteTextView.onFilterComplete(AutoCompleteTextView.java:932)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:285)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.os.Handler.dispatchMessage(Handler.java:99)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.os.Looper.loop(Looper.java:137)
08-16 22:21:23.244: E/AndroidRuntime(25475):    at android.app.ActivityThread.main(ActivityThread.java:4507)

Any ideas on what could be wrong?

Bhagwad Jal Park
  • 1,093
  • 1
  • 13
  • 22
  • 1
    Though I still have no solution, I just extended AutoCompleteTextView, caught the error in onFilterComplete in a try/catch loop surrounding the "super" statement, ignored it and moved on. I have no idea why it occurred or how to handle it. Problem solved. Messy though. Would appreciate a more elegant solution. – Bhagwad Jal Park Aug 17 '12 at 04:04
  • I am doing something similar HERE!! http://stackoverflow.com/questions/12854336/autocompletetextview-backed-by-cursorloader – Etienne Lawlor Oct 12 '12 at 07:36
  • @BhagwadJalPark I have solved this problem as you have. The solution proposed by Tony (checking for closed state in OnLoadFinished) did not work for me. Here is the wrapper class I wrote per your insight: https://gist.github.com/esilverberg/5606551 – esilver May 19 '13 at 03:29

1 Answers1

7

OnLoadFinished seems to get called sometimes with a dead cursor - if you put a test for isClosed() on the cursor you get passed you'll find it's closed in one in (some large number) attempts.

Unfortunately the 'standard' code to put in OnLoadFinished immediately does a changeCursor() on the adapter and, well, what follows is chaos, stackdumps, pestilence, etc.

My solution isn't any prettier than your try/catch.. ignore the bogus OnLoadFinished and risk the end user getting a blank UI.

Tony Hoyle
  • 609
  • 6
  • 4
  • 1
    Thanks for that tidbit. For this particular case, I've dumped loadermanager/cursorloaer entirely and implemented another way to do this with setfilterqueryprovider. But your solution seems to be the best way to go. Perhaps we can submit a bug report somewhere? – Bhagwad Jal Park Aug 18 '12 at 22:42