Android sqlite 事务级别,android:使用ContentResolver时的sqlite事务

正如Kaciula所提到的,由于android 2.1使用ContentProviderOperation,因此可以非常干净地执行基于事务的多表插入。

当您构建ContentProviderOperation对象时,可以调用.WithValueBackReference(FieldName,Refnr)。当使用applybatch应用该操作时,结果是随insert()调用提供的contentValues对象将注入一个整数。该整数将使用字段名字符串进行键控,其值将从以前应用的ContentProvider属性的ContentProviderResult中检索,该属性由refnr索引。

请参阅下面的代码示例。在示例中,在表1中插入一行,然后在表2中插入行时,将生成的ID(在本例中为“1”)用作值。为了简洁起见,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 list = new

ArrayList();

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 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

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值