在自己的ContentProvider类里,重写applyBatch方法,加入事务:
1 @Override 2 public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation>operations) 3 throws OperationApplicationException{ 4 SQLiteDatabase db = mOpenHelper.getWritableDatabase(); 5 db.beginTransaction(); 6 try{ 7 ContentProviderResult[]results = super.applyBatch(operations); 8 db.setTransactionSuccessful(); 9 return results; 10 }finally { 11 db.endTransaction(); 12 } 13 }
在处理数据时使用ContentProviderOperation:
1 ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
然后循环加入数据库操作:
1 ContentValues value = new ContentValues(); 2 ops.add(ContentProviderOperation.newUpdate(MyProvider.CONTENT_URI) 3 .withSelection("_id='" + entry.getId() + "'", null) 4 .withValues(value) 5 .withYieldAllowed(true) 6 .build());
然后提交操作:
1 try { 2 mContext.getContentResolver().applyBatch(MyProvider.AUTHORITY, ops); 3 } catch (RemoteException e) { 4 e.printStackTrace(); 5 } catch (OperationApplicationException e) { 6 e.printStackTrace(); 7 }
这样,用了事务之后,数据库效率会大大提升。