Android: SQLite transactions when using ContentResolver

Bostone picture Bostone · Feb 9, 2010 · Viewed 19.1k times · Source

The goal: refresh database from XML data

The process:

  • Start transaction
  • Delete all existing rows from the tables
  • Per each main element of parsed XML insert row into main table and get PK
  • Per each child of the main element insert record into 2nd table providing FK from the previous step
  • Commit transaction

Pretty standard stuff as far as db operations. The problem is that CRUD operations are not done within ContentProvider but rather using ContentResolver so the insert for example looks like resolver.insert(CONTENT_URI, contentValues). The ContentResolver API doesn't seem to have anything pertained to transaction and I cannot use bulkInsert since I'm inserting in 2 tables intermittently (plus I want to have delete inside the transaction as well).

I was thinking of registering my customized ContentProvider as listener by using registerContentObserver but since ContentResolver#acquireProvider methods are hidden how do I obtain the right reference?

Am I out of luck?

Answer

Catalin Morosan picture Catalin Morosan · Oct 15, 2010

I've seen that in the source code of Google I/O application, they override ContentProvider's applyBatch() method and use transactions inside of it. So, you create a batch of ContentProviderOperation s and then call getContentResolver().applyBatch(uri_authority, batch).

I'm planning to use this approach to see how it works. I'm curious if anyone else has tried it.