Migrating to CursorLoader & LoaderManager for Auto

2019-05-31 09:12发布

问题:

I have an AutoCompleteTextView, which shows dropdown list of suggestions taken from a SQLiteDatabase query. At the moment it uses SimpleCursorAdapter, however there are several problems with it (I have a separate question about the issue here: SimpleCursorAdapter issue - "java.lang.IllegalStateException: trying to requery an already closed cursor").

Nevertheless, I was advised to look in the direction of CursorLoader and LoaderManager, and I've tried it, yet couldn't make it work. I'd be grateful if someone would guide/recommend/show the right way of migrating my code below to CursorLoader/LoaderManager concept. Any kind of help very appreciated!

mAdapter = new SimpleCursorAdapter(this,
                R.layout.dropdown_text,
                null,
                new String[]{CITY_COUNTRY_NAME},
                new int[]{R.id.text}, 0);
        mAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> listView, View view, int position, long id) {
                Cursor cursor = (Cursor) listView.getItemAtPosition(position);
                cityCountryName = cursor.getString(cursor.getColumnIndexOrThrow(CITY_COUNTRY_NAME));
                mAutoCompleteTextView.setText(cityCountryName);
                JSONWeatherTask task = new JSONWeatherTask();
                task.execute(new String[]{cityCountryName});
            }
        });
        mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            public Cursor runQuery(CharSequence sequence) {
                String constraint = sequence.toString();
                String queryString = "SELECT " + ID + ", " + CITY_ID + ", " + CITY_COUNTRY_NAME + " FROM " + TABLE_1;
                constraint = constraint.trim() + "%";
                queryString += " WHERE " + CITY_COUNTRY_NAME + " LIKE ?";
                String params[] = {constraint};
                try {
                    Cursor cursor = database.rawQuery(queryString, params);
                    if (cursor != null) {
                        startManagingCursor(cursor);
                        cursor.moveToFirst();
                        return cursor;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
                return null;
            }
        });
        mAutoCompleteTextView.setAdapter(mAdapter);

Here is the whole project for the reference (you can make a pull request there, if you wish): Open Weather App

回答1:

Unfortunately, here on SO nobody came up with a solution, yet a colleague (he doesn't have an SO account) made a pull request with the migration fixes. It works perfectly, and I decided to post the correct answer here as well.

If you're interested in how these improvements look inside the actual code, you're welcome to visit the original open source project page on GitHub: Open Weather App

This is the new adapter:

mAdapter = new SimpleCursorAdapter(this,
                R.layout.dropdown_text,
                null,
                new String[]{CITY_COUNTRY_NAME},
                new int[]{R.id.text},0);
        mAdapter.setFilterQueryProvider(new FilterQueryProvider() {
            @Override
            public Cursor runQuery(CharSequence constraint) {
                if (constraint != null) {
                    if (constraint.length() >= 3 && !TextUtils.isEmpty(constraint)) {
                        Bundle bundle = new Bundle();
                        String query = charArrayUpperCaser(constraint);
                        bundle.putString(CITY_ARGS, query);
                        getLoaderManager().restartLoader(0, bundle, MainActivity.this).forceLoad();
                    }
                }
                return null;
            }
        });

This is the onCreateLoader() callback:

@Override
public android.content.Loader<Cursor> onCreateLoader(int id, Bundle args) {
    String s = args.getString(CITY_ARGS);
    WeatherCursorLoader loader = null;
    if (s != null && !TextUtils.isEmpty(s)) {
        loader = new WeatherCursorLoader(this, database, s);
    }
    return loader;
}

Custom CursorLoader itself:

private static class WeatherCursorLoader extends CursorLoader {

    private SQLiteDatabase mSQLiteDatabase;
    private String mQuery;

    WeatherCursorLoader(Context context, SQLiteDatabase cDatabase, String s) {
        super(context);
        mSQLiteDatabase = cDatabase;
        mQuery = s + "%";
        Log.d(TAG, "WeatherCursorLoader: " + mQuery);
    }


    @Override
    public Cursor loadInBackground() {
        return mSQLiteDatabase.query(TABLE_1, mProjection,
                CITY_COUNTRY_NAME + " like ?", new String[] {mQuery},
                null, null, null, "50");
    }
}