Android:使用 ContentResolver 时的 SQLite 事务 [英] Android: SQLite transactions when using ContentResolver
问题描述
目标:从 XML 数据刷新数据库
The goal: refresh database from XML data
过程:
- 开始交易
- 删除表中的所有现有行
- 根据解析的 XML 的每个主要元素插入行到主表中并获得 PK
- 每个主要元素的每个子元素插入记录到第二个表中,提供上一步的 FK
- 提交交易
- 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
就数据库操作而言,这是非常标准的东西.问题是 CRUD 操作不是在 ContentProvider
内完成,而是使用 ContentResolver
所以插入看起来像 resolver.insert(CONTENT_URI, contentValues)
.ContentResolver API 似乎没有任何与事务有关的东西,我不能使用 bulkInsert
,因为我间歇性地插入 2 个表(另外我想在里面有 delete
交易也是如此).
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).
我想通过使用 registerContentObserver
将我自定义的 ContentProvider
注册为侦听器,但由于 ContentResolver#acquireProvider
方法被隐藏,我该如何获取正确的参考?
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?
我不走运了吗?
推荐答案
我看到在 Google I/O 应用程序的源代码中,它们覆盖了 ContentProvider
的 applyBatch()
方法并在其中使用事务.因此,您创建了一批 ContentProviderOperation
,然后调用 getContentResolver().applyBatch(uri_authority, batch)
.
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.
这篇关于Android:使用 ContentResolver 时的 SQLite 事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!