我制作了自己的 contentprovider,我通过多次插入将大量数据一次性放入其中。
该应用程序将从外部源接收数据,此时我收到大约 30 个项目(因此是插入的 30 倍)。
现在我注意到这需要很多宝贵的时间(大约 3 秒,每次插入 100 毫秒)。
如何提高内容提供者的速度?我已经尝试将它们全部插入在一起,但最多需要 5 秒。
提前致谢。
最佳答案
将 insertBulk
中的所有内容包装到交易中。
例子:
SQLiteDatabase sqlDB = mDB.getWritableDatabase();
sqlDB.beginTransaction();
try {
for (ContentValues cv : values) {
long newID = sqlDB.insertOrThrow(table, null, cv);
if (newID <= 0) {
throw new SQLException("Failed to insert row into " + uri);
}
}
sqlDB.setTransactionSuccessful();
getContext().getContentResolver().notifyChange(uri, null);
numInserted = values.length;
} finally {
sqlDB.endTransaction();
}
bulkInsert
默认不使用事务,因为默认行为只是调用 insert
:
Override this to handle requests to insert a set of new rows, or the default implementation will iterate over the values and call insert(Uri, ContentValues) on each of them.
关于Android contentprovider 插入需要很多时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8343154/