Reputation: 1486
I'm developing an application which relies on database (local) - and this database updates frequently.
What I'm trying to achieve is: Suppose the data is shown in a listview. I want the listview to update the dataset as soon as any change in the database happens (or a specific table to be precise).
So far I've thought of these options:
Which is the best way to achieve consistent and immediate updates without blocking the UI (performance)?
Upvotes: 2
Views: 468
Reputation: 5900
If performance is crucial for your app you should take a look on Realm for Android database. It provides better efficiency than SQLite and you can use RealmChangeListener
to listen for changes in the database.
Upvotes: 0
Reputation: 1486
As suggested by @Karakuri created a custom CursorLoader by extending CursorLoader class without ContentProvider.
Here's the solution:
CustomCursorLoader.class
public class CustomCursorLoader extends CursorLoader {
private final ForceLoadContentObserver forceLoadContentObserver = new ForceLoadContentObserver();
public CustomCursorLoader(Context context, Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
super(context, uri, projection, selection, selectionArgs, sortOrder);
}
@Override
public Cursor loadInBackground() {
Cursor cursor = /* get cursor from DBHandler class */;
cursor.setNotificationUri(getContext().getContentResolver(), CONTENT_URI);
if (cursor != null) {
cursor.getCount();
cursor.registerContentObserver(forceLoadContentObserver);
}
return cursor;
}
}
Every time you make a change to DB, do:
getContentResolver().notifyChange(CONTENT_URI, null);
In Activity class:
implement interface LoaderManager.LoaderCallbacks<Cursor>
initiate loader getLoaderManager().initLoader(0, null, this);
and override these methods:
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CustomCursorLoader(this, CONTENT_URI, null, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
customCursorLoaderAdapter.swapCursor(data);
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
customCursorLoaderAdapter.swapCursor(null);
}
extend CursorAdapter
class to create listview adapter and you're done.
Upvotes: 1