Search in sources :

Example 31 with ContentProviderResult

use of android.content.ContentProviderResult in project Meltdown by phubbard.

the class ItemProvider method applyBatch.

/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside
 * a {@link SQLiteDatabase} transaction. All changes will be rolled back if
 * any single one fails.
 *
 * @note this is from the Google iosched (Google IO 2012) code.
 */
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    Long tzero = System.currentTimeMillis();
    Log.i(TAG, "Bulk ops called");
    if (helper == null)
        helper = new dbHelper(getContext(), DB_VERSION);
    final SQLiteDatabase db = helper.getWritableDatabase();
    db.beginTransaction();
    try {
        final int numOperations = operations.size();
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            try {
                results[i] = operations.get(i).apply(this, results, i);
            } catch (SQLiteConstraintException sqe) {
            // Log.d(TAG, "ignoring constraint");
            }
        }
        db.setTransactionSuccessful();
        Long deltat = System.currentTimeMillis() - tzero;
        Double ops_per_sec = operations.size() / ((float) deltat / 1000.0);
        Log.i(TAG, String.format("%d msec to do %d ops, %7.2f ops per second", deltat, operations.size(), ops_per_sec));
        return results;
    } finally {
        db.endTransaction();
    }
}
Also used : ContentProviderResult(android.content.ContentProviderResult) SQLiteDatabase(android.database.sqlite.SQLiteDatabase) SQLiteConstraintException(android.database.sqlite.SQLiteConstraintException)

Example 32 with ContentProviderResult

use of android.content.ContentProviderResult in project iosched by google.

the class PostSignInUpgradeService method onHandleIntent.

@Override
protected void onHandleIntent(@Nullable Intent intent) {
    if (intent == null) {
        return;
    }
    String accountName = intent.getStringExtra(KEY_ACCOUNT_NAME);
    if (accountName == null) {
        return;
    }
    // TODO: It would be better if the default value for the account in
    // the non-signed in case was not "null". When that is modified update this.
    String previousAccountName = null;
    // The task is to upgrade all user data that was associated with a non-logged in user
    // and update it to the signed in user.
    ArrayList<ContentProviderOperation> ops = new ArrayList<>(3);
    // noinspection ConstantConditions
    ops.add(ContentProviderOperation.newUpdate(ScheduleContractHelper.addOverrideAccountUpdateAllowed(MySchedule.buildMyScheduleUri(previousAccountName))).withValue(MySchedule.MY_SCHEDULE_ACCOUNT_NAME, accountName).build());
    // noinspection ConstantConditions
    ops.add(ContentProviderOperation.newUpdate(ScheduleContractHelper.addOverrideAccountUpdateAllowed(MyFeedbackSubmitted.buildMyFeedbackSubmittedUri(previousAccountName))).withValue(MyFeedbackSubmitted.MY_FEEDBACK_SUBMITTED_ACCOUNT_NAME, accountName).build());
    // Delete any reservations (should be none)
    // noinspection ConstantConditions
    ops.add(ContentProviderOperation.newDelete(MyReservations.buildMyReservationUri(previousAccountName)).withSelection(MyReservations.MY_RESERVATION_ACCOUNT_NAME, null).build());
    try {
        ContentProviderResult[] results = getContentResolver().applyBatch(ScheduleContract.CONTENT_AUTHORITY, ops);
        if (LogUtils.LOGGING_ENABLED) {
            for (ContentProviderResult res : results) {
                LOGV(TAG, "Result of update: uri: " + res.uri + " count: " + res.count);
            }
        }
    } catch (RemoteException | OperationApplicationException e) {
        LOGE(TAG, "Unexpected exception upgrading the user data to signed in user", e);
    } finally {
        // Note: Once we are done with the upgrade we trigger a manual sync for user data
        SyncHelper.requestManualSync(true);
    }
}
Also used : ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) ArrayList(java.util.ArrayList) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Example 33 with ContentProviderResult

use of android.content.ContentProviderResult in project SeriesGuide by UweTrottmann.

the class SeriesGuideProvider method applyBatch.

/**
 * Apply the given set of {@link ContentProviderOperation}, executing inside a {@link
 * SQLiteDatabase} transaction. All changes will be rolled back if any single one fails.
 */
@NonNull
@Override
public ContentProviderResult[] applyBatch(@NonNull ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    final int numOperations = operations.size();
    if (numOperations == 0) {
        return new ContentProviderResult[0];
    }
    SgRoomDatabase room = SgRoomDatabase.getInstance(getContext());
    database = room.getOpenHelper().getWritableDatabase();
    room.beginTransaction();
    try {
        applyingBatch.set(true);
        final ContentProviderResult[] results = new ContentProviderResult[numOperations];
        for (int i = 0; i < numOperations; i++) {
            final ContentProviderOperation operation = operations.get(i);
            // do not yield as a pre-caution to not break Room invalidation tracker
            // if (i > 0 && operation.isYieldAllowed()) {
            // database.yieldIfContendedSafely();
            // }
            results[i] = operation.apply(this, results, i);
        }
        room.setTransactionSuccessful();
        return results;
    } finally {
        applyingBatch.set(false);
        room.endTransaction();
    }
}
Also used : ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) NonNull(androidx.annotation.NonNull)

Example 34 with ContentProviderResult

use of android.content.ContentProviderResult in project stetho by facebook.

the class APODContentProvider method applyBatch.

@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations) throws OperationApplicationException {
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();
    db.beginTransaction();
    try {
        ContentProviderResult[] results = super.applyBatch(operations);
        db.setTransactionSuccessful();
        return results;
    } finally {
        db.endTransaction();
        notifyChange();
    }
}
Also used : ContentProviderResult(android.content.ContentProviderResult) SQLiteDatabase(android.database.sqlite.SQLiteDatabase)

Example 35 with ContentProviderResult

use of android.content.ContentProviderResult in project packages_apps_Contacts by AOKP.

the class ContactSaveService method saveContact.

private void saveContact(Intent intent) {
    RawContactDeltaList state = intent.getParcelableExtra(EXTRA_CONTACT_STATE);
    boolean isProfile = intent.getBooleanExtra(EXTRA_SAVE_IS_PROFILE, false);
    Bundle updatedPhotos = intent.getParcelableExtra(EXTRA_UPDATED_PHOTOS);
    if (state == null) {
        Log.e(TAG, "Invalid arguments for saveContact request");
        return;
    }
    int saveMode = intent.getIntExtra(EXTRA_SAVE_MODE, -1);
    // Trim any empty fields, and RawContacts, before persisting
    final AccountTypeManager accountTypes = AccountTypeManager.getInstance(this);
    RawContactModifier.trimEmpty(state, accountTypes);
    Uri lookupUri = null;
    final ContentResolver resolver = getContentResolver();
    boolean succeeded = false;
    // Keep track of the id of a newly raw-contact (if any... there can be at most one).
    long insertedRawContactId = -1;
    // Attempt to persist changes
    Integer result = RESULT_FAILURE;
    ArrayList<Long> rawContactsList = new ArrayList<Long>();
    boolean isCardOperation = false;
    for (int i = 0; i < state.size(); i++) {
        final RawContactDelta entity = state.get(i);
        final String accountType = entity.getValues().getAsString(RawContacts.ACCOUNT_TYPE);
        final String accountName = entity.getValues().getAsString(RawContacts.ACCOUNT_NAME);
        rawContactsList.add(entity.getRawContactId());
        if (accountType != null && ExchangeAccountType.isExchangeType(accountType))
            removeDisplayName(entity);
        final int subscription = MoreContactUtils.getSubscription(accountType, accountName);
        isCardOperation = (subscription != SubscriptionManager.INVALID_SUBSCRIPTION_ID) ? true : false;
        if (isCardOperation) {
            result = doSaveToSimCard(entity, resolver, subscription);
            Log.d(TAG, "doSaveToSimCard result is  " + result);
        }
    }
    int tries = 0;
    while (tries++ < PERSIST_TRIES) {
        if (result == RESULT_SUCCESS || result == RESULT_FAILURE) {
            try {
                // Build operations and try applying
                final ArrayList<CPOWrapper> diffWrapper = state.buildDiffWrapper();
                final ArrayList<ContentProviderOperation> diff = Lists.newArrayList();
                for (CPOWrapper cpoWrapper : diffWrapper) {
                    diff.add(cpoWrapper.getOperation());
                }
                if (DEBUG) {
                    Log.v(TAG, "Content Provider Operations:");
                    for (ContentProviderOperation operation : diff) {
                        Log.v(TAG, operation.toString());
                    }
                }
                int numberProcessed = 0;
                boolean batchFailed = false;
                final ContentProviderResult[] results = new ContentProviderResult[diff.size()];
                while (numberProcessed < diff.size()) {
                    final int subsetCount = applyDiffSubset(diff, numberProcessed, results, resolver);
                    if (subsetCount == -1) {
                        Log.w(TAG, "Resolver.applyBatch failed in saveContacts");
                        batchFailed = true;
                        break;
                    } else {
                        numberProcessed += subsetCount;
                    }
                }
                if (batchFailed) {
                    // Retry save
                    continue;
                }
                final long rawContactId = getRawContactId(state, diffWrapper, results);
                if (rawContactId == -1) {
                    throw new IllegalStateException("Could not determine RawContact ID after save");
                }
                // We don't have to check to see if the value is still -1.  If we reach here,
                // the previous loop iteration didn't succeed, so any ID that we obtained is bogus.
                insertedRawContactId = getInsertedRawContactId(diffWrapper, results);
                if (isProfile) {
                    // Since the profile supports local raw contacts, which may have been completely
                    // removed if all information was removed, we need to do a special query to
                    // get the lookup URI for the profile contact (if it still exists).
                    Cursor c = resolver.query(Profile.CONTENT_URI, new String[] { Contacts._ID, Contacts.LOOKUP_KEY }, null, null, null);
                    if (c == null) {
                        continue;
                    }
                    try {
                        if (c.moveToFirst()) {
                            final long contactId = c.getLong(0);
                            final String lookupKey = c.getString(1);
                            lookupUri = Contacts.getLookupUri(contactId, lookupKey);
                        }
                    } finally {
                        c.close();
                    }
                } else {
                    final Uri rawContactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
                    lookupUri = RawContacts.getContactLookupUri(resolver, rawContactUri);
                }
                if (lookupUri != null) {
                    Log.v(TAG, "Saved contact. New URI: " + lookupUri);
                }
                // We can change this back to false later, if we fail to save the contact photo.
                succeeded = true;
                break;
            } catch (RemoteException e) {
                // Something went wrong, bail without success
                Log.e(TAG, "Problem persisting user edits", e);
                break;
            } catch (IllegalArgumentException e) {
                // This is thrown by applyBatch on malformed requests
                Log.e(TAG, "Problem persisting user edits", e);
                showToast(R.string.contactSavedErrorToast);
                break;
            } catch (OperationApplicationException e) {
                // Version consistency failed, re-parent change and try again
                Log.w(TAG, "Version consistency failed, re-parenting: " + e.toString());
                final StringBuilder sb = new StringBuilder(RawContacts._ID + " IN(");
                boolean first = true;
                final int count = state.size();
                for (int i = 0; i < count; i++) {
                    Long rawContactId = state.getRawContactId(i);
                    if (rawContactId != null && rawContactId != -1) {
                        if (!first) {
                            sb.append(',');
                        }
                        sb.append(rawContactId);
                        first = false;
                    }
                }
                sb.append(")");
                if (first) {
                    throw new IllegalStateException("Version consistency failed for a new contact", e);
                }
                final RawContactDeltaList newState = RawContactDeltaList.fromQuery(isProfile ? RawContactsEntity.PROFILE_CONTENT_URI : RawContactsEntity.CONTENT_URI, resolver, sb.toString(), null, null);
                state = RawContactDeltaList.mergeAfter(newState, state);
                // Update the new state to use profile URIs if appropriate.
                if (isProfile) {
                    for (RawContactDelta delta : state) {
                        delta.setProfileQueryUri();
                    }
                }
            }
        }
    }
    // the ContactProvider already knows about newly-created contacts.
    if (updatedPhotos != null) {
        for (String key : updatedPhotos.keySet()) {
            Uri photoUri = updatedPhotos.getParcelable(key);
            long rawContactId = Long.parseLong(key);
            // replace the bogus ID with the new one that we actually saved the contact at.
            if (rawContactId < 0) {
                rawContactId = insertedRawContactId;
            }
            // If the save failed, insertedRawContactId will be -1
            if (rawContactId < 0 || !saveUpdatedPhoto(rawContactId, photoUri, saveMode)) {
                succeeded = false;
            }
        }
    }
    Intent callbackIntent = intent.getParcelableExtra(EXTRA_CALLBACK_INTENT);
    if (callbackIntent != null) {
        if (succeeded) {
            // Mark the intent to indicate that the save was successful (even if the lookup URI
            // is now null).  For local contacts or the local profile, it's possible that the
            // save triggered removal of the contact, so no lookup URI would exist..
            callbackIntent.putExtra(EXTRA_SAVE_SUCCEEDED, true);
        }
        callbackIntent.setData(lookupUri);
        deliverCallback(callbackIntent);
    }
}
Also used : ContentProviderResult(android.content.ContentProviderResult) ContentProviderOperation(android.content.ContentProviderOperation) CopyOnWriteArrayList(java.util.concurrent.CopyOnWriteArrayList) ArrayList(java.util.ArrayList) Cursor(android.database.Cursor) Uri(android.net.Uri) RawContactDelta(com.android.contacts.common.model.RawContactDelta) ContentResolver(android.content.ContentResolver) CPOWrapper(com.android.contacts.common.model.CPOWrapper) Bundle(android.os.Bundle) Intent(android.content.Intent) RawContactDeltaList(com.android.contacts.common.model.RawContactDeltaList) AccountTypeManager(com.android.contacts.common.model.AccountTypeManager) RemoteException(android.os.RemoteException) OperationApplicationException(android.content.OperationApplicationException)

Aggregations

ContentProviderResult (android.content.ContentProviderResult)39 ContentProviderOperation (android.content.ContentProviderOperation)30 OperationApplicationException (android.content.OperationApplicationException)22 ArrayList (java.util.ArrayList)20 RemoteException (android.os.RemoteException)17 SQLiteDatabase (android.database.sqlite.SQLiteDatabase)12 ContentValues (android.content.ContentValues)9 Uri (android.net.Uri)9 ContentResolver (android.content.ContentResolver)6 Intent (android.content.Intent)6 NonNull (android.support.annotation.NonNull)6 BroadcastReceiver (android.content.BroadcastReceiver)4 Context (android.content.Context)4 IntentFilter (android.content.IntentFilter)4 PackageMonitor (com.android.internal.content.PackageMonitor)4 CopyOnWriteArrayList (java.util.concurrent.CopyOnWriteArrayList)3 Test (org.junit.Test)3 ContentProvider (android.content.ContentProvider)2 OperationInfo (com.android.calendar.AsyncQueryServiceHelper.OperationInfo)2 OrgProperties (com.orgzly.org.OrgProperties)2