1
我有一个覆盖bulkInsert()
的MyContentProvider类。在此方法中,我使用SQLite事务向数据库中插入大约4,000行,这在三星Galaxy S4设备上大约需要25秒。Android - contentResolver.notifyChange()放慢性能
然而,当我除去从我bulkInsert()
方法这一行...
getContext().getContentResolver().notifyChange(insertedId, null);
...总插入时间降低到约1或2秒。
那么,有没有更好的方法可以拨打notifyChange()
?
我曾尝试调用它在另一个线程,这样的...
new Thread(new Runnable() {
public void run() {
getContext().getContentResolver().notifyChange(insertedId, null);
}
}).start();
...但它仍然缓慢,而由于某种原因,导致一个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();
}
}
还通知“目录uri”不是“项目uri”(不是:'content:// host/table/1',而是整个'content:// host/table') – Selvin 2014-11-06 14:46:27
好,好东西! – 2014-11-06 16:29:05
要应用该解决方案,我已将此添加到我的finally块的末尾:if(numSuccessfulInsertions> 0)getContext()。getContentResolver()。notifyChange(uri,null);' – 2014-11-06 16:57:16