TheKalpit
TheKalpit

Reputation: 1486

Frequently updating SQLite DB and Listview (efficiency)

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:

  1. SQLiteOpenHelper class: whenever an update/insert is done it'll notify the activity to update listview via BroadcastReceiver.
  2. ContentProvider with CursorLoader (haven't used it before so a little skeptical)
  3. Something else? Please suggest.

Which is the best way to achieve consistent and immediate updates without blocking the UI (performance)?

Upvotes: 2

Views: 468

Answers (2)

amukhachov
amukhachov

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

TheKalpit
TheKalpit

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

Related Questions