主细节使用ContentResolver.applyBatch()?

Dan*_*Dan 21 android android-contentprovider

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

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

我想出的内容如下所示:

Master Uri:content://com.foobar.masterdetail/master
Detail 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

谢谢.

phr*_*eed 17

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

.withValue(Detail.MASTER_ID, /* WHAT GOES HERE? */)
Run Code Online (Sandbox Code Playgroud)

.withValueBackReference(Detail.MASTER_ID, 0)
Run Code Online (Sandbox Code Playgroud)

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