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