22

我想知道是否可以在同一操作中使用 android.content.ContentResolver.applyBatch() 方法将主记录和详细记录保存到内容提供者,其中 providers 参数中的后续 ContentProviderOperation 项目取决于先前项目的结果。

我遇到的问题是,在调用 ContentProviderOperation.newInsert(Uri) 方法并且 Uri 是不可变的时,实际的 Uri 是未知的。

我想出的如下所示:

主 Uri:content://com.foobar.masterdetail/master
详细 Uri:content://com.foobar.masterdetail/master/#/detail

ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
operations.add(ContentProviderOperation.newInsert(intent.getData())
    .withValue(Master.NAME, "")
    .withValue(Master.VALUE, "")
    .build());
operations.add(ContentProviderOperation.newInsert(intent.getData()
        .buildUpon()
        .appendPath("#") /* ACTUAL VALUE NOT KNOWN UNTIL MASTER ROW IS SAVED */
        .appendPath("detail")
        .build())
    .withValue(Detail.MASTER_ID, /* WHAT GOES HERE? */)
    .withValue(Detail.NAME, "")
    .withValue(Detail.VALUE, "")
    .build());
ContentProviderResult[] results = this.getContentResolver().applyBatch(MasterDetail.AUTHORITY, operations);
for (ContentProviderResult result : results) {
    Uri test = result.uri;
}

在我的内容提供程序中,我重写了 applyBatch() 方法,以便将操作包装在事务中。

这是可能的还是有更好的方法来做到这一点?

谢谢。

4

1 回答 1

17

从操作数组中的项目产生的每个结果都由它在数组中的索引标识。后续操作可以通过 withValueBackReference() 方法引用这些结果。

.withValue(Detail.MASTER_ID, /* WHAT GOES HERE? */)

变成

.withValueBackReference(Detail.MASTER_ID, 0)

这种用法的完整示例可以在示例 ContactManager中找到。0 是从中获取值的 ContentProviderOperation 的索引。

于 2010-12-28T18:08:21.823 回答