ban*_*ing 1 sqlite performance android android-contentresolver android-contentprovider
我有一个覆盖的MyContentProvider类bulkInsert().在这种方法中,我使用SQLite事务在数据库中插入大约4,000行,这在Samsung Galaxy S4设备上大约需要25秒.
但是,当我从我的方法中删除此行时bulkInsert()...
getContext().getContentResolver().notifyChange(insertedId, null);
...总插入时间下降到大约1或2秒.
那么,有更好的方式来打电话notifyChange()吗?
我试过在另一个线程中调用它,像这样......
new Thread(new Runnable() {
public void run() {
getContext().getContentResolver().notifyChange(insertedId, null);
}
}).start();
Run Code Online (Sandbox Code Playgroud)
......但它仍然缓慢,而由于某种原因,导致一个OutOfMemoryError.
为了完整,这是我的bulkInsert()方法......
@Override
public int bulkInsert(Uri uri, ContentValues[] valuesArray) {
/*
* Open a read / write database to support the transaction.
*/
SQLiteDatabase db = dbHelper.getWritableDatabase();
String tableName;
switch (uriMatcher.match(uri)) {
case BRANDS_SEARCH:
tableName = BRAND_NAMES_TABLE;
break;
case PRODUCTS_SEARCH:
tableName = PRODUCTS_TABLE;
break;
case PARENT_COMPANIES_SEARCH:
tableName = PARENT_COMPANIES_TABLE;
break;
case PRODUCTS_DATA_SEARCH:
tableName = PRODUCTS_DATA_TABLE;
break;
default:
//break;
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
/*
* Begin the transaction
*/
db.beginTransaction();
int numSuccessfulInsertions = 0;
try {
for (int i = 0; i < valuesArray.length; i++) {
/*
* Insert the values into the table
*/
long rowId = db.insert(tableName, null, valuesArray[i]);
if (rowId > -1) {
/*
* Increment numSuccessfulInsertions
*/
numSuccessfulInsertions++;
/*
* Construct the URI of the newly inserted row.
*/
Uri insertedId = ContentUris.withAppendedId(uri, rowId);
/*
* Notify any observers of the change in the data set.
*/
getContext().getContentResolver().notifyChange(insertedId, null);
}
else {
/*
* Don't give up (as not all insert attempts need to succeed)
*/
//throw new Exception("Could not insert row");
}
}
/*
* Return number of successful insertions
*/
return numSuccessfulInsertions;
}
catch(Exception e) {
Log.e(LOG_TAG, "bulkInsert exception", e);
/*
* Return number of successful insertions
*/
return numSuccessfulInsertions;
}
finally {
/*
* Some (or all) insertion attempts succeeded
*/
db.setTransactionSuccessful();
/*
* Always end the transaction
*/
db.endTransaction();
}
}
Run Code Online (Sandbox Code Playgroud)
通知一次进行批量操作,而不是每次插入的记录一次.将您的调用移至notifyChange,使其跟随for循环.
| 归档时间: |
|
| 查看次数: |
510 次 |
| 最近记录: |