kaciulaが述べたように、Android 2.1以降、ContentProviderOperationを使用することで、トランザクションベースのマルチテーブル挿入をかなりクリーンに行うことができます。
ContentProviderOperationオブジェクトを作成するときに、.withValueBackReference(fieldName、refNr)を呼び出すことができます。applyBatchを使用して操作を適用すると、insert()呼び出しで提供されるContentValuesオブジェクトに整数が注入されます。整数はfieldName文字列でキー設定され、その値は、refNrによってインデックス付けされた以前に適用されたContentProviderOperationのContentProviderResultから取得されます。
以下のコードサンプルを参照してください。サンプルでは、行がtable1に挿入され、結果のID(この場合は「1」)がテーブル2に行を挿入するときに値として使用されます。簡潔にするために、ContentProviderはデータベースに接続されていません。ContentProviderには、トランザクション処理を追加するのに適したプリントアウトがあります。
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
}