Android ContentProvider calls bursts of setNotificationUri() to CursorAdapter when many rows are inserted with a batch operation

后端 未结 3 785
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-08 01:51

I have a custom ContentProvider which manages the access to a SQLite database. To load the content of a database table in a ListFragment, I use the

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-08 02:30

    I found a simpler solution that I discovered from Google's I/O app. You just have to override the applyBatch method in your ContentProvider and perform all the operations in a transaction. Notifications are not sent until the transaction commits, which results in minimizing the number of ContentProvider change-notifications that are sent out:

    @Override
    public ContentProviderResult[] applyBatch(ArrayList operations)
            throws OperationApplicationException {
    
        final SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            final int numOperations = operations.size();
            final ContentProviderResult[] results = new ContentProviderResult[numOperations];
            for (int i = 0; i < numOperations; i++) {
                results[i] = operations.get(i).apply(this, results, i);
            }
            db.setTransactionSuccessful();
            return results;
        } finally {
            db.endTransaction();
        }
    }
    

提交回复
热议问题