How to update the interface after changing the database

I am developing an application based on the Google IO architecture using the first approach. Mostly I have a Service , ContentProvider with SQLite DB support, and I also use Loader s.

I need a way to update the interface when changes occur in my database. For example, a user might want to add an item to their cart. After I insert the item ID into the basket table, I want to update the interface. Which approach should I use? So far I have seen very little information about ContentObserver . Is that the way?

+7
android android-contentprovider android-sqlite android-loader
source share
2 answers

In the query method of your ContentProvider attach the listener to the returned cursor:

  Cursor cursor = queryBuilder.query(dbConnection, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(getContext().getContentResolver(), uri); 

Then in your insert / update / delete methods use the following code:

  final long objectId = dbConnection.insertOrThrow(ObjectTable.TABLE_NAME, null, values); final Uri newObjectUri = ContentUris.withAppendedId(OBJECT_CONTENT_URI, objectId ); getContext().getContentResolver().notifyChange(newObjectUri , null); 

Your CursorLoader will be notified, and OnLoadFinished(Loader, Cursor) will be called again.

If you are not using Loader , ContentObserver is a path with a few lines of code that you notify about changes to the DB (but you will need to manually request it).

  private ContentObserver objectObserver = new ContentObserver(new Handler()) { @Override public void onChange(boolean selfChange) { super.onChange(selfChange); restartObjectLoader(); } }; 

Remember to call onResume() :

  getContentResolver().registerContentObserver(ObjectProvider.OBJECT_CONTENT_URI, false, objectObserver); 

and in onPause() :

  getContentResolver().unregisterContentObserver(objectObserver); 

Update: UI Changes This is a larger topic because it depends on the Adapter that you use to populate a ListView or RecyclerView .

CursorAdapter In onLoadFinished(Loader loader, Cursor data)

  mAdapter.swapCursor(data); 

ArrayAdapter In onLoadFinished(Loader loader, Cursor data)

  Object[] objects = transformCursorToArray(data); //you need to write this method mAdapter.setObjects(objects); //You need to wrie this method in your implementation on the adapter mAdapter.notifyDataSetChange(); 

RecyclerView.Adapter In onLoadFinished(Loader loader, Cursor data)

  Object[] objects = transformCursorToArray(data); //you need to write this method //Here you have more mAdapter.notify....() 

Read here for a different way to alert RecyclerView.Adapter .

+6
source share

If you use a list, you can fill out the adapter again and install it in your list. Or try reporting a dataset change.

+2
source share

All Articles