主细节使用ContentResolver.applyBatch()?

时间:2010-07-11 22:25:36

标签: android android-contentprovider

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

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

我想出的内容如下所示:

Uri大师:内容://com.foobar.masterdetail/master
细节Uri:内容://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()方法,以便将操作包装在事务中。

这可能或有更好的方法吗?

感谢。

1 个答案:

答案 0 :(得分:17)

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

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

变为

.withValueBackReference(Detail.MASTER_ID, 0)

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

相关问题