Example usage for android.util Log VERBOSE

List of usage examples for android.util Log VERBOSE

Introduction

In this page you can find the example usage for android.util Log VERBOSE.

Prototype

int VERBOSE

To view the source code for android.util Log VERBOSE.

Click Source Link

Document

Priority constant for the println method; use Log.v.

Usage

From source file:org.readium.sdk.lcp.StatusDocumentProcessing.java

private void registerDevice(final DoneCallback doneCallback_registerDevice) {

    String deviceID = m_deviceIDManager.getDeviceID();
    String deviceNAME = m_deviceIDManager.getDeviceNAME();

    boolean doRegister = false;
    if (m_statusDocument_LINK_REGISTER == null) {
        doRegister = false;//from  w  w w. j  a v  a2 s. com
    } else if (m_statusDocument_STATUS.equals("ready")) {
        doRegister = true;
    } else if (m_statusDocument_STATUS.equals("active")) {

        String deviceIDForStatusDoc = m_deviceIDManager.checkDeviceID(m_statusDocument_ID);

        if (deviceIDForStatusDoc == null) {
            doRegister = true;
        } else if (!deviceIDForStatusDoc.equals(deviceID)) { // this should really never happen ... but let's ensure anyway.
            doRegister = true;
        }
    }

    if (!doRegister) {
        doneCallback_registerDevice.Done(false);
        return;
    }

    String url = m_statusDocument_LINK_REGISTER.m_href;
    if (m_statusDocument_LINK_REGISTER.m_templated.equals("true")) {

        // URLEncoder.encode() doesn't generate %20 for space character (instead: '+')
        // So we use android.net.Uri's appendQueryParameter() instead (see below)
        //        try {
        //            deviceID = URLEncoder.encode(deviceID, "UTF-8");
        //            deviceNAME = URLEncoder.encode(deviceNAME, "UTF-8");
        //        } catch (Exception ex) {
        //            // noop
        //        }
        //        url = url.replace("{?id,name}", "?id=" + deviceID + "&name=" + deviceNAME);

        url = url.replace("{?id,name}", ""); // TODO: smarter regexp?
        url = Uri.parse(url).buildUpon().appendQueryParameter("id", deviceID)
                .appendQueryParameter("name", deviceNAME).build().toString();
    }

    Locale currentLocale = getCurrentLocale();
    String langCode = currentLocale.toString().replace('_', '-');
    langCode = langCode + ",en-US;q=0.7,en;q=0.5";

    Future<Response<InputStream>> request = Ion.with(m_context).load("POST", url)
            .setLogging("Readium Ion", Log.VERBOSE)

            //.setTimeout(AsyncHttpRequest.DEFAULT_TIMEOUT) //30000
            .setTimeout(6000)

            // TODO: comment this in production! (this is only for testing a local HTTP server)
            //.setHeader("X-Add-Delay", "2s")

            // LCP / LSD server with message localization
            .setHeader("Accept-Language", langCode)

            // QUERY params (templated URI)
            //                        .setBodyParameter("id", dID)
            //                        .setBodyParameter("name", dNAME)

            .asInputStream().withResponse()

            // UI thread
            .setCallback(new FutureCallback<Response<InputStream>>() {
                @Override
                public void onCompleted(Exception e, Response<InputStream> response) {

                    InputStream inputStream = response != null ? response.getResult() : null;
                    int httpResponseCode = response != null ? response.getHeaders().code() : 0;
                    if (e != null || inputStream == null || httpResponseCode < 200 || httpResponseCode >= 300) {

                        doneCallback_registerDevice.Done(false);
                        return;
                    }

                    try {

                        StringWriter writer = new StringWriter();
                        IOUtils.copy(inputStream, writer, "UTF-8");
                        String json = writer.toString().trim();

                        boolean okay = parseStatusDocumentJson(json);

                        if (okay && m_statusDocument_STATUS.equals("active")) {
                            m_deviceIDManager.recordDeviceID(m_statusDocument_ID);
                        }

                        doneCallback_registerDevice.Done(true);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        doneCallback_registerDevice.Done(false);
                    } finally {
                        try {
                            inputStream.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            // ignore
                        }
                    }
                }
            });
}

From source file:com.android.screenspeak.eventprocessor.ProcessorFocusAndSingleTap.java

/**
 * Attempts to place focus within a new window.
 *//*from  w ww. ja  v  a 2  s. c o m*/
private boolean ensureFocusConsistency() {
    AccessibilityNodeInfoCompat root = null;
    AccessibilityNodeInfoCompat focused = null;

    try {
        root = AccessibilityServiceCompatUtils.getRootInAccessibilityFocusedWindow(mService);
        if (root == null) {
            return false;
        }

        // First, see if we've already placed accessibility focus.
        focused = root.findFocus(AccessibilityNodeInfo.FOCUS_ACCESSIBILITY);
        if (focused != null) {
            if (AccessibilityNodeInfoUtils.shouldFocusNode(focused)) {
                return true;
            }

            LogUtils.log(Log.VERBOSE, "Clearing focus from invalid node");
            PerformActionUtils.performAction(focused, AccessibilityNodeInfo.ACTION_CLEAR_ACCESSIBILITY_FOCUS);
        }

        return false;
    } finally {
        AccessibilityNodeInfoUtils.recycleNodes(root, focused);
    }
}

From source file:com.android.talkback.SpeechController.java

private void speak(FeedbackItem item, int queueMode, UtteranceCompleteRunnable completedAction) {

    // If this FeedbackItem is flagged as NO_SPEECH, ignore speech and
    // immediately process earcons and haptics without disrupting the speech
    // queue.//from www .jav  a 2 s  . c om
    // TODO: Consider refactoring non-speech feedback out of
    // this class entirely.
    if (item.hasFlag(FeedbackItem.FLAG_NO_SPEECH)) {
        for (FeedbackFragment fragment : item.getFragments()) {
            playEarconsFromFragment(fragment);
            playHapticsFromFragment(fragment);
        }

        return;
    }

    if (item.hasFlag(FeedbackItem.FLAG_SKIP_DUPLICATE) && hasItemOnQueueOrSpeaking(item)) {
        return;
    }

    item.setUninterruptible(queueMode == QUEUE_MODE_UNINTERRUPTIBLE);
    item.setCompletedAction(completedAction);

    boolean currentFeedbackInterrupted = false;
    if (shouldClearQueue(item, queueMode)) {
        FeedbackItemFilter filter = getFeedbackItemFilter(item, queueMode);
        // Call onUtteranceComplete on each queue item to be cleared.
        ListIterator<FeedbackItem> iterator = mFeedbackQueue.listIterator(0);
        while (iterator.hasNext()) {
            FeedbackItem currentItem = iterator.next();
            if (filter.accept(currentItem)) {
                iterator.remove();
                notifyItemInterrupted(currentItem);
            }
        }

        if (mCurrentFeedbackItem != null && filter.accept(mCurrentFeedbackItem)) {
            notifyItemInterrupted(mCurrentFeedbackItem);
            currentFeedbackInterrupted = true;
        }
    }

    mFeedbackQueue.add(item);
    if (mSpeechListener != null) {
        mSpeechListener.onUtteranceQueued(item);
    }

    // If TTS isn't ready, this should be the only item in the queue.
    if (!mFailoverTts.isReady()) {
        LogUtils.log(this, Log.ERROR, "Attempted to speak before TTS was initialized.");
        return;
    }

    if ((mCurrentFeedbackItem == null) || currentFeedbackInterrupted) {
        mCurrentFragmentIterator = null;
        speakNextItem();
    } else {
        LogUtils.log(this, Log.VERBOSE, "Queued speech item, waiting for \"%s\"",
                mCurrentFeedbackItem.getUtteranceId());
    }
}

From source file:com.google.android.marvin.screenspeak.ScreenSpeakService.java

@Override
protected boolean onGesture(int gestureId) {
    if (!isServiceActive())
        return false;

    if (LogUtils.LOG_LEVEL <= Log.VERBOSE) {
        Log.v(LOGTAG, String.format("Recognized gesture %s", gestureId));
    }/*from w  w  w.j  a va 2 s.c om*/

    if (mKeyboardSearchManager != null && mKeyboardSearchManager.onGesture())
        return true;
    mAnalytics.onGesture(gestureId);
    mFeedbackController.playAuditory(R.raw.gesture_end);

    // Gestures always stop global speech on API 16. On API 17+ we silence
    // on TOUCH_INTERACTION_START.
    // TODO(KM): Will this negatively affect something like Books?
    if (Build.VERSION.SDK_INT <= 16) {
        interruptAllFeedback();
    }

    mMenuManager.onGesture(gestureId);
    mGestureController.onGesture(gestureId);
    return true;
}

From source file:com.google.android.marvin.mytalkback.CursorController.java

private AccessibilityNodeInfoCompat navigateFrom(AccessibilityNodeInfoCompat node, int direction) {
    if (node == null) {
        return null;
    }/*from  w  w  w  .  ja v a2 s . com*/

    AccessibilityNodeInfoCompat next = null;

    try {
        // Be cautious and always clear the list of seen nodes.
        AccessibilityNodeInfoUtils.recycleNodes(mNavigateSeenNodes);

        next = NodeFocusFinder.focusSearch(node, direction);

        while ((next != null) && !AccessibilityNodeInfoUtils.shouldFocusNode(mService, next)) {
            if (mNavigateSeenNodes.contains(next)) {
                LogUtils.log(this, Log.ERROR, "Found duplicate during traversal: %s", next.getInfo());
                // TODO(alanv): Should we return null here or just stop traversing?
                break;
            }

            LogUtils.log(this, Log.VERBOSE, "Search strategy rejected node: %s", next.getInfo());

            mNavigateSeenNodes.add(next);

            next = NodeFocusFinder.focusSearch(next, direction);
        }

        return next;
    } finally {
        AccessibilityNodeInfoUtils.recycleNodes(mNavigateSeenNodes);
    }
}

From source file:com.googlecode.eyesfree.brailleback.DefaultNavigationMode.java

private boolean activateNode(AccessibilityNodeInfoCompat node, int position) {
    if (node == null) {
        return false;
    }/*from w ww .ja  v  a2s  . c o  m*/
    AccessibilityNodeInfoRef current = AccessibilityNodeInfoRef.unOwned(node);
    try {
        do {
            LogUtils.log(this, Log.VERBOSE, "Considering to click: %s", current.get().getInfo());
            int supportedActions = current.get().getActions();
            int action = 0;
            // For edit texts, the click action doesn't currently focus
            // the view, so we special case it here.
            // TODO: Revise when that changes.
            if (AccessibilityNodeInfoUtils.nodeMatchesClassByType(mAccessibilityService, current.get(),
                    EditText.class)) {
                if ((supportedActions & AccessibilityNodeInfo.ACTION_FOCUS) != 0) {
                    action = AccessibilityNodeInfo.ACTION_FOCUS;
                } else {
                    // Put accessibility focus on the field.  If it is
                    // already focused and the IME is selected, that will
                    // activate the editing.
                    action = AccessibilityNodeInfo.ACTION_ACCESSIBILITY_FOCUS;
                }
            } else if (position >= 0 && isSelfBrailled(current.get())
                    && (supportedActions & AccessibilityNodeInfo.ACTION_CLICK) != 0) {
                // Generate a fake "action". For instance, a click at
                // position 33 maps to -275000033.
                // TODO: Remove this hack when a better way to pass this
                // information exists.
                int fakeAction = ACTION_BRAILLE_CLICK_MAX - position;
                if (fakeAction < ACTION_BRAILLE_CLICK_MIN) {
                    LogUtils.log(this, Log.WARN, "underflow activating node %s at position %d", current.get(),
                            position);
                    fakeAction = ACTION_BRAILLE_CLICK_MIN;
                } else if (fakeAction > ACTION_BRAILLE_CLICK_MAX) {
                    LogUtils.log(this, Log.WARN, "overflow activating node %s at position %d", current.get(),
                            position);
                    fakeAction = ACTION_BRAILLE_CLICK_MAX;
                }
                if (WebInterfaceUtils.performSpecialAction(current.get(), fakeAction)) {
                    return true;
                }
            } else if ((supportedActions & AccessibilityNodeInfo.ACTION_CLICK) != 0) {
                action = AccessibilityNodeInfo.ACTION_CLICK;
            }
            if (action != 0 && current.get().performAction(action)) {
                return true;
            } else {
                LogUtils.log(this, Log.VERBOSE, "Action %d failed", action);
            }
        } while (current.parent());
    } finally {
        current.recycle();
    }
    LogUtils.log(this, Log.VERBOSE, "Click action failed");
    return false;
}

From source file:org.readium.sdk.lcp.StatusDocumentProcessing.java

private void fetchAndInjectUpdatedLicense(final DoneCallback doneCallback_fetchAndInjectUpdatedLicense) {

    if (m_statusDocument_LINK_LICENSE == null) {
        doneCallback_fetchAndInjectUpdatedLicense.Done(false);
        return;//from w ww.  j  a v  a2s.  c  om
    }

    final String url = m_statusDocument_LINK_LICENSE.m_href;

    Locale currentLocale = getCurrentLocale();
    String langCode = currentLocale.toString().replace('_', '-');
    langCode = langCode + ",en-US;q=0.7,en;q=0.5";

    Future<Response<InputStream>> request = Ion.with(m_context).load("GET", url)
            .setLogging("Readium Ion", Log.VERBOSE)

            //.setTimeout(AsyncHttpRequest.DEFAULT_TIMEOUT) //30000
            .setTimeout(6000)

            // TODO: comment this in production! (this is only for testing a local HTTP server)
            //.setHeader("X-Add-Delay", "2s")

            // LCP / LSD server with message localization
            .setHeader("Accept-Language", langCode)

            .asInputStream().withResponse()

            // UI thread
            .setCallback(new FutureCallback<Response<InputStream>>() {
                @Override
                public void onCompleted(Exception e, Response<InputStream> response) {

                    InputStream inputStream = response != null ? response.getResult() : null;
                    int httpResponseCode = response != null ? response.getHeaders().code() : 0;
                    if (e != null || inputStream == null || httpResponseCode < 200 || httpResponseCode >= 300) {

                        doneCallback_fetchAndInjectUpdatedLicense.Done(false);
                        return;
                    }

                    try {
                        StringWriter writer = new StringWriter();
                        IOUtils.copy(inputStream, writer, "UTF-8");
                        String json = writer.toString().trim();

                        // new LCP license
                        mLcpService.injectLicense(mBookPath, json);

                        // forces re-check of LSD, now with updated LCP timestamp
                        mLicense.setStatusDocumentProcessingFlag(false);

                        doneCallback_fetchAndInjectUpdatedLicense.Done(true);

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        doneCallback_fetchAndInjectUpdatedLicense.Done(false);
                    } finally {
                        try {
                            inputStream.close();
                        } catch (IOException ex) {
                            ex.printStackTrace();
                            // ignore
                        }
                    }
                }
            });
}

From source file:com.radicaldynamic.groupinform.services.DatabaseService.java

private void removePlaceholders(HashMap<String, JSONObject> placeholders) {
    final String tt = t + "removePlaceholders(): ";

    for (Map.Entry<String, JSONObject> entry : placeholders.entrySet()) {
        if (entry.getValue().optString("createdBy", null) == null
                || entry.getValue().optString("dateCreated", null) == null) {
            // Remove old style (unowned) placeholders immediately
            try {
                getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                if (Collect.Log.VERBOSE)
                    Log.v(Collect.LOGTAG, tt + "removed old-style placeholder " + entry.getKey());
            } catch (Exception e) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to remove old-style placeholder");
                e.printStackTrace();/*from www  .  j  a  v a2  s . c  om*/
            }
        } else if (entry.getValue().optString("createdBy")
                .equals(Collect.getInstance().getInformOnlineState().getDeviceId())) {
            // Remove placeholders owned by me immediately
            try {
                getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                if (Collect.Log.VERBOSE)
                    Log.v(Collect.LOGTAG, tt + "removed my placeholder " + entry.getKey());
            } catch (Exception e) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to remove my placeholder");
                e.printStackTrace();
            }
        } else {
            // Remove placeholders owned by other people if they are stale (older than a day)
            SimpleDateFormat sdf = new SimpleDateFormat(Generic.DATETIME);
            Calendar calendar = Calendar.getInstance();

            try {
                calendar.setTime(sdf.parse(entry.getValue().optString("dateCreated")));

                if (calendar.getTimeInMillis() - Calendar.getInstance().getTimeInMillis() > TIME_24_HOURS) {
                    try {
                        getDb().delete(entry.getKey(), entry.getValue().optString("_rev"));
                        if (Collect.Log.VERBOSE)
                            Log.v(Collect.LOGTAG, tt + "removed stale placeholder " + entry.getKey());
                    } catch (Exception e) {
                        if (Collect.Log.ERROR)
                            Log.e(Collect.LOGTAG, tt + "unable to remove stale placeholder");
                        e.printStackTrace();
                    }
                }
            } catch (ParseException e1) {
                if (Collect.Log.ERROR)
                    Log.e(Collect.LOGTAG, tt + "unable to parse dateCreated: " + e1.toString());
                e1.printStackTrace();
            }
        }
    }
}

From source file:com.concentriclivers.mms.com.android.mms.transaction.MessagingNotification.java

private static final void addMmsNotificationInfos(Context context, Set<Long> threads) {
    ContentResolver resolver = context.getContentResolver();

    // This query looks like this when logged:
    // I/Database(  147): elapsedTime4Sql|/data/data/com.android.providers.telephony/databases/
    // mmssms.db|0.362 ms|SELECT thread_id, date, _id, sub, sub_cs FROM pdu WHERE ((msg_box=1
    // AND seen=0 AND (m_type=130 OR m_type=132))) ORDER BY date desc

    Cursor cursor = SqliteWrapper.query(context, resolver, Mms.CONTENT_URI, MMS_STATUS_PROJECTION,
            NEW_INCOMING_MM_CONSTRAINT, null, Mms.DATE + " desc");

    if (cursor == null) {
        return;//  w  w  w .j a  v  a  2s . c om
    }

    try {
        while (cursor.moveToNext()) {

            long msgId = cursor.getLong(COLUMN_MMS_ID);
            Uri msgUri = Mms.CONTENT_URI.buildUpon().appendPath(Long.toString(msgId)).build();
            String address = AddressUtils.getFrom(context, msgUri);

            Contact contact = Contact.get(address, false);
            if (contact.getSendToVoicemail()) {
                // don't notify, skip this one
                continue;
            }

            String subject = getMmsSubject(cursor.getString(COLUMN_SUBJECT), cursor.getInt(COLUMN_SUBJECT_CS));
            long threadId = cursor.getLong(COLUMN_THREAD_ID);
            long timeMillis = cursor.getLong(COLUMN_DATE) * 1000;

            if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
                Log.d(TAG, "addMmsNotificationInfos: count=" + cursor.getCount() + ", addr = " + address
                        + ", thread_id=" + threadId);
            }

            // Extract the message and/or an attached picture from the first slide
            Bitmap attachedPicture = null;
            String messageBody = null;
            int attachmentType = WorkingMessage.TEXT;
            try {
                GenericPdu pdu = sPduPersister.load(msgUri);
                if (pdu != null && pdu instanceof MultimediaMessagePdu) {
                    SlideshowModel slideshow = SlideshowModel.createFromPduBody(context,
                            ((MultimediaMessagePdu) pdu).getBody());
                    attachmentType = getAttachmentType(slideshow);
                    SlideModel firstSlide = slideshow.get(0);
                    if (firstSlide != null) {
                        if (firstSlide.hasImage()) {
                            int maxDim = dp2Pixels(MAX_BITMAP_DIMEN_DP);
                            attachedPicture = firstSlide.getImage().getBitmap(maxDim, maxDim);
                        }
                        if (firstSlide.hasText()) {
                            messageBody = firstSlide.getText().getText();
                        }
                    }
                }
            } catch (final MmsException e) {
                Log.e(TAG, "MmsException loading uri: " + msgUri, e);
            }

            NotificationInfo info = getNewMessageNotificationInfo(context, false /* isSms */, address,
                    messageBody, subject, threadId, timeMillis, attachedPicture, contact, attachmentType);

            sNotificationSet.add(info);

            threads.add(threadId);
        }
    } finally {
        cursor.close();
    }
}

From source file:com.android.contacts.ContactSaveService.java

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;/*from ww w.j  a  va 2 s .co m*/
    }

    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
    int tries = 0;
    while (tries++ < PERSIST_TRIES) {
        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.isLoggable(TAG, Log.VERBOSE)) {
                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
            FeedbackHelper.sendFeedback(this, TAG, "Problem persisting user edits", e);
            break;

        } catch (IllegalArgumentException e) {
            // This is thrown by applyBatch on malformed requests
            FeedbackHelper.sendFeedback(this, 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();
                }
            }
        }
    }

    // Now save any updated photos.  We do this at the end to ensure that
    // 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);

            // If the raw-contact ID is negative, we are saving a new raw-contact;
            // 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);
    }
}