您的位置:首页 > 移动开发 > Android开发

提高android ContentProvider的效率

2013-01-25 11:54 295 查看
在自己的ContentProvider类里,重写applyBatch方法,加入事务:

@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation>operations)
throws OperationApplicationException{
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try{
ContentProviderResult[]results = super.applyBatch(operations);
db.setTransactionSuccessful();
return results;
}finally {
db.endTransaction();
}
}


在处理数据时使用ContentProviderOperation:

ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();


然后循环加入数据库操作:

ContentValues value = new ContentValues();
ops.add(ContentProviderOperation.newUpdate(MyProvider.CONTENT_URI)
.withSelection("_id='" + entry.getId() + "'", null)
.withValues(value)
.withYieldAllowed(true)
.build());


然后提交操作:

try {
mContext.getContentResolver().applyBatch(MyProvider.AUTHORITY, ops);
} catch (RemoteException e) {
e.printStackTrace();
} catch (OperationApplicationException e) {
e.printStackTrace();
}


这样,用了事务之后,数据库效率会大大提升。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: