Migrating to CursorLoader & LoaderManager for AutoCompleteTextView with SQLiteDatabase

戏子无情 提交于 2019-12-06 15:50:48

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");
    }
} 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!