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

[转]提高android ContentProvider的效率

2013-06-04 17:38 330 查看
ContentProviderOperation,用ContentProviderOperation.Builder.withYieldAllowed (true)来允许当前的数据库操作可以被挂机
批量操作容易长时间占用数据库, 所以要写这个屈服点来保证其他要读库的程序来中断这个操作

在自己的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();
}
}

这样,用了事务之后,数据库效率会大大提升。
转自/article/7094953.html

android sqlite批量插入数据速度解决方案

最近在做android项目的时候遇到一个问题,应用程序初始化时需要批量的向sqlite中插入大量数,导致应用启动过慢。

android使用的是sqlite数据库,sqlite是比较轻量级的数据库,在Google了之后发现,sqlite事务处理的问题,在sqlite插入数据的时候默认一条语句就是一个事务,有多少条数据就有多少次磁盘操作。我的应用初始5000条记录也就是要5000次读写磁盘操作。

解决方法:

添加事务处理,把5000条插入作为一个事务

dataBase.beginTransaction(); //手动设置开始事务

//数据插入操作循环

dataBase.setTransactionSuccessful(); //设置事务处理成功,不设置会自动回滚不提交

dataBase.endTransaction(); //处理完成

将数据库「倒出来」:

sqlite3 film.db ".dump" > output.sql

利用输出的资料,建立一个一模一样的数据库(加上以上指令,就是标准的SQL数据库

备份了):

sqlite3 film.db < output.sql

在大量插入资料时,你可能会需要先打这个指令:

begin;

插入完资料后要记得打这个指令,资料才会写进数据库中:

commit;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: