正如kaciula提到的那樣,通過使用ContentProviderOperation可以很方便地完成基於事務的多表插入。
當您構建ContentProviderOperation對象時,可以調用.withValueBackReference(fieldName,refNr)。當使用applyBatch應用操作時,結果是由insert()調用提供的ContentValues對象將注入一個整數。該整數將用fieldName字符串鍵入,並且其值從以前應用的ContentProviderOperation的ContentProviderResult中檢索,由refNr索引。
請參考下面的代碼示例。在示例中,將一行插入到table1中,然後將結果ID(本例中爲「1」)用作在表2中插入行時的值。爲簡潔起見,ContentProvider未連接到數據庫。在ContentProvider中,有打印輸出適合添加事務處理。使用ContentProviderClient.getLocalContentProvider:
public class BatchTestActivity extends Activity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayList<ContentProviderOperation> list = new
ArrayList<ContentProviderOperation>();
list.add(ContentProviderOperation.
newInsert(BatchContentProvider.FIRST_URI).build());
ContentValues cv = new ContentValues();
cv.put("name", "second_name");
cv.put("refId", 23);
// In this example, "refId" in the contentValues will be overwritten by
// the result from the first insert operation, indexed by 0
list.add(ContentProviderOperation.
newInsert(BatchContentProvider.SECOND_URI).
withValues(cv).withValueBackReference("refId", 0).build());
try {
getContentResolver().applyBatch(
BatchContentProvider.AUTHORITY, list);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}
}
}
public class BatchContentProvider extends ContentProvider {
private static final String SCHEME = "content://";
public static final String AUTHORITY = "com.test.batch";
public static final Uri FIRST_URI =
Uri.parse(SCHEME + AUTHORITY + "/" + "table1");
public static final Uri SECOND_URI =
Uri.parse(SCHEME + AUTHORITY + "/" + "table2");
public ContentProviderResult[] applyBatch(
ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
System.out.println("starting transaction");
ContentProviderResult[] result;
try {
result = super.applyBatch(operations);
} catch (OperationApplicationException e) {
System.out.println("aborting transaction");
throw e;
}
System.out.println("ending transaction");
return result;
}
public Uri insert(Uri uri, ContentValues values) {
// this printout will have a proper value when
// the second operation is applied
System.out.println("" + values);
return ContentUris.withAppendedId(uri, 1);
}
// other overrides omitted for brevity
}
看到這一點:http://stackoverflow.com/questions/4655291/semantics-of-withvaluebackreference – 2011-10-25 15:31:12
你有沒有找到一個解決這個?我找不到可行的解決方案 – jamesc 2011-11-11 21:10:01