使用事务操作android 数据库

来源:互联网 发布:怎样用c语言编写游戏 编辑:程序博客网 时间:2024/05/16 12:00
使用事务添加联系人
1. 在添加联系人得时候是分多次访问Provider,如果在过程中出现异常,会出现数据不完整的情况,这些操作应该放在一次事务中
2. 使用ContentResolver的applyBatch(String authority,ArrayList<ContentProviderOperation> operations) 方法可以将多个操作在一个事务中执行
示例:
        //使用事务添加联系人  
public void testInsertBatch() throws Exception {  
    ContentResolver resolver = getContext().getContentResolver();  
 
    ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();  
 
    ContentProviderOperation operation1 = ContentProviderOperation //  
            .newInsert(Uri.parse("content://com.android.contacts/raw_contacts")) //  
            .withValue("_id", null) //  
            .build();  
    operations.add(operation1);  
 
    ContentProviderOperation operation2 = ContentProviderOperation //  
            .newInsert(Uri.parse("content://com.android.contacts/data")) //  
            .withValueBackReference("raw_contact_id", 0) //  
            .withValue("data2", "ZZH") //  
            .withValue("mimetype", "vnd.android.cursor.item/name") //  
            .build();  
    operations.add(operation2);  
      
    ContentProviderOperation operation3 = ContentProviderOperation //  
            .newInsert(Uri.parse("content://com.android.contacts/data")) //  
            .withValueBackReference("raw_contact_id", 0) //  
            .withValue("data1", "18612312312") //  
            .withValue("data2", "2") //  
            .withValue("mimetype", "vnd.android.cursor.item/phone_v2") //  
            .build();  
    operations.add(operation3);  
 
    ContentProviderOperation operation4 = ContentProviderOperation //  
            .newInsert(Uri.parse("content://com.android.contacts/data")) //  
            .withValueBackReference("raw_contact_id", 0) //  
            .withValue("data1", "www.2cto.com") //  
            .withValue("data2", "2") //  
            .withValue("mimetype", "vnd.android.cursor.item/email_v2") //  
            .build();  
    operations.add(operation4);  
 
    // 在事务中对多个操作批量执行  
    resolver.applyBatch("com.android.contacts", operations);  
原创粉丝点击