How to automatically re-query with LoaderManager

2019-03-05 20:24发布

I have an app that shows data from a SQLite DB and the data changes constantly, so obviously, I thought I should use a LoaderManager to show the data.

do I read a bit about using the LoaderManager with SQLite and saw Alex Lokwood's answer about implementing the CursorLoader and using it, and I saw the this answer about using a CursorLoader directly to an SQLite DB instead of a ContentProvider and started using commonsware's Loaderex.

I created this class for showing the data in a ListView:

public class LandingPageActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
    ListView list;
    SimpleCursorAdapter mAdapter;

    private SQLiteCursorLoader loader = null;
    private Context mContext;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_friends_and_threads);
        list = (ListView) findViewById(R.id.list);
        mContext = LandingPageActivity.this;

        mAdapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, null,
                new String[] { Properties.Title.columnName }, new int[] { android.R.id.text1 }, 0);

        list.setAdapter(mAdapter);
        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        Context c = mContext;
        String query = "SELECT * FROM TABLE_NAME";
        SQLiteOpenHelper db = DatabaseHelper.getDatabase();
        loader = new SQLiteCursorLoader(c, db, query, null);
        return loader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
        mAdapter.changeCursor(arg1);
    }

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

the problem starts when the database is changed from a 'BroadcastListener' while the activity is still running.

basically what I'm looking for is real-time observing of the database changes but it seems (also from the Android Documentation that I need to call the restartLoader function when I want to re-query the db).

is there a way to automate re-query behind the scenes?

UPDATE:

My initial thought was to create a function that restarts the loader, something like this:

public static void restartLoader(Context context){
    context.getSupportLoaderManager().restartLoader(0, null, LandingPageActivity.this);
}

but it seems crud and not the best way of doing this.

1条回答
Juvenile、少年°
2楼-- · 2019-03-05 20:45

the problem starts when the database is changed from a 'BroadcastListener' while the activity is still running... is there a way to automate re-query behind the scenes?

Have the BroadcastReceiver use the insert(), update(), replace(), and delete() methods on SQLiteCursorLoader to modify the database. Then, the Cursor will be re-loaded automatically.

查看更多
登录 后发表回答