Example usage for android.content ContentValues getAsLong

List of usage examples for android.content ContentValues getAsLong

Introduction

In this page you can find the example usage for android.content ContentValues getAsLong.

Prototype

public Long getAsLong(String key) 

Source Link

Document

Gets a value and converts it to a Long.

Usage

From source file:at.bitfire.ical4android.AndroidTask.java

protected void populateTask(ContentValues values)
        throws FileNotFoundException, RemoteException, ParseException {
    task.uid = values.getAsString(Tasks._UID);
    task.summary = values.getAsString(Tasks.TITLE);
    task.location = values.getAsString(Tasks.LOCATION);

    if (values.containsKey(Tasks.GEO)) {
        String geo = values.getAsString(Tasks.GEO);
        if (geo != null)
            task.geoPosition = new Geo(geo);
    }/*from   w ww.  j a va 2s  .c  o  m*/
    ;

    task.description = StringUtils.stripToNull(values.getAsString(Tasks.DESCRIPTION));
    task.url = StringUtils.stripToNull(values.getAsString(Tasks.URL));

    String organizer = values.getAsString(Tasks.ORGANIZER);
    if (!TextUtils.isEmpty(organizer))
        try {
            task.organizer = new Organizer("mailto:" + values.getAsString(Tasks.ORGANIZER));
        } catch (URISyntaxException e) {
            Log.w(TAG, "Invalid ORGANIZER email", e);
        }

    Integer priority = values.getAsInteger(Tasks.PRIORITY);
    if (priority != null)
        task.priority = priority;

    Integer classification = values.getAsInteger(Tasks.CLASSIFICATION);
    if (classification != null)
        switch (classification) {
        case Tasks.CLASSIFICATION_PUBLIC:
            task.classification = Clazz.PUBLIC;
            break;
        case Tasks.CLASSIFICATION_CONFIDENTIAL:
            task.classification = Clazz.CONFIDENTIAL;
            break;
        default:
            task.classification = Clazz.PRIVATE;
        }

    Long completed = values.getAsLong(Tasks.COMPLETED);
    if (completed != null)
        // COMPLETED must always be a DATE-TIME
        task.completedAt = new Completed(new DateTime(completed));

    Integer percentComplete = values.getAsInteger(Tasks.PERCENT_COMPLETE);
    if (percentComplete != null)
        task.percentComplete = percentComplete;

    Integer status = values.getAsInteger(Tasks.STATUS);
    if (status != null)
        switch (status) {
        case Tasks.STATUS_IN_PROCESS:
            task.status = Status.VTODO_IN_PROCESS;
            break;
        case Tasks.STATUS_COMPLETED:
            task.status = Status.VTODO_COMPLETED;
            break;
        case Tasks.STATUS_CANCELLED:
            task.status = Status.VTODO_CANCELLED;
            break;
        default:
            task.status = Status.VTODO_NEEDS_ACTION;
        }

    boolean allDay = false;
    if (values.getAsInteger(Tasks.IS_ALLDAY) != null)
        allDay = values.getAsInteger(Tasks.IS_ALLDAY) != 0;

    String tzID = values.getAsString(Tasks.TZ);
    TimeZone tz = (tzID != null) ? DateUtils.tzRegistry.getTimeZone(tzID) : null;

    Long createdAt = values.getAsLong(Tasks.CREATED);
    if (createdAt != null)
        task.createdAt = createdAt;

    Long lastModified = values.getAsLong(Tasks.LAST_MODIFIED);
    if (lastModified != null)
        task.lastModified = lastModified;

    Long dtStart = values.getAsLong(Tasks.DTSTART);
    if (dtStart != null) {
        long ts = dtStart;

        Date dt;
        if (allDay)
            dt = new Date(ts);
        else {
            dt = new DateTime(ts);
            if (tz != null)
                ((DateTime) dt).setTimeZone(tz);
        }
        task.dtStart = new DtStart(dt);
    }

    Long due = values.getAsLong(Tasks.DUE);
    if (due != null) {
        long ts = due;

        Date dt;
        if (allDay)
            dt = new Date(ts);
        else {
            dt = new DateTime(ts);
            if (tz != null)
                ((DateTime) dt).setTimeZone(tz);
        }
        task.due = new Due(dt);
    }

    String duration = values.getAsString(Tasks.DURATION);
    if (duration != null)
        task.duration = new Duration(new Dur(duration));

    String rDate = values.getAsString(Tasks.RDATE);
    if (rDate != null)
        task.getRDates().add((RDate) DateUtils.androidStringToRecurrenceSet(rDate, RDate.class, allDay));

    String exDate = values.getAsString(Tasks.EXDATE);
    if (exDate != null)
        task.getExDates().add((ExDate) DateUtils.androidStringToRecurrenceSet(exDate, ExDate.class, allDay));

    String rRule = values.getAsString(Tasks.RRULE);
    if (rRule != null)
        task.rRule = new RRule(rRule);
}

From source file:com.roamprocess1.roaming4world.service.SipNotifications.java

public void showNotificationForMissedCall(ContentValues callLog) {
    int icon = android.R.drawable.stat_notify_missed_call;
    CharSequence tickerText = context.getText(R.string.missed_call);
    long when = System.currentTimeMillis();

    if (missedCallNotification == null) {
        missedCallNotification = new NotificationCompat.Builder(context);
        missedCallNotification.setSmallIcon(icon);
        missedCallNotification.setTicker(tickerText);
        missedCallNotification.setWhen(when);
        missedCallNotification.setOnlyAlertOnce(true);
        missedCallNotification.setAutoCancel(true);
        missedCallNotification.setDefaults(Notification.DEFAULT_ALL);
    }//ww w . j  a  va2 s.  c  om

    System.out.println("showNotificationForMissedCall");
    Intent notificationIntent = new Intent("com.roamprocess1.roaming4world.R4wHome.R4w_ACTIVITY");

    //   Intent notificationIntent = new Intent(SipManager.ACTION_SIP_CALLLOG);
    System.out.println("Misscall Notification");
    //notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);

    String remoteContact = callLog.getAsString(CallLog.Calls.NUMBER);
    System.out.println("remoteContact  vlaue " + remoteContact);

    String[] parts = remoteContact.split("@");
    String part1 = parts[0]; // 004
    String[] part3 = part1.split(":");
    String part5 = part3[1];
    System.out.println("part5 ==" + part5);

    long accId = callLog.getAsLong(SipManager.CALLLOG_PROFILE_ID_FIELD);
    missedCallNotification.setContentTitle(formatNotificationTitle(R.string.missed_call, accId));
    missedCallNotification.setContentText(formatRemoteContactString(part5));
    System.out.println("remoteContact  vlaue ==" + remoteContact);
    missedCallNotification.setContentIntent(contentIntent);

    notificationManager.notify(CALLLOG_NOTIF_ID, missedCallNotification.build());
}

From source file:org.anhonesteffort.flock.sync.calendar.EventFactory.java

protected static ComponentETagPair<Calendar> getEventComponent(String path, ContentValues eventValues)
        throws InvalidComponentException {
    Calendar calendar = new Calendar();
    VEvent vEvent = new VEvent();
    TimeZoneRegistry registry = TimeZoneRegistryFactory.getInstance().createRegistry();

    calendar.getProperties().add(Version.VERSION_2_0);
    handleAttachPropertiesForCopiedRecurrenceWithExceptions(eventValues, vEvent);

    String uidText = eventValues.getAsString(CalendarContract.Events._SYNC_ID);
    if (!StringUtils.isEmpty(uidText)) {
        Uid eventUid = new Uid(uidText);
        vEvent.getProperties().add(eventUid);
    }// w  w w  . j a va2 s  . c om

    try {

        String organizerText = eventValues.getAsString(CalendarContract.Events.ORGANIZER);
        if (StringUtils.isNotEmpty(organizerText)) {
            URI organizerEmail = new URI("mailto", organizerText, null);
            Organizer organizer = new Organizer(organizerEmail);
            vEvent.getProperties().add(organizer);
        }

    } catch (URISyntaxException e) {
        Log.e(TAG, "caught exception while parsing URI from organizerText", e);
        throw new InvalidComponentException("caught exception while parsing URI from organizerText", false,
                CalDavConstants.CALDAV_NAMESPACE, path, e);
    }

    String summaryText = eventValues.getAsString(CalendarContract.Events.TITLE);
    if (StringUtils.isNotEmpty(summaryText)) {
        Summary summary = new Summary(summaryText);
        vEvent.getProperties().add(summary);
    }

    String locationText = eventValues.getAsString(CalendarContract.Events.EVENT_LOCATION);
    if (StringUtils.isNotEmpty(locationText)) {
        Location location = new Location(locationText);
        vEvent.getProperties().add(location);
    }

    String descriptionText = eventValues.getAsString(CalendarContract.Events.DESCRIPTION);
    if (StringUtils.isNotEmpty(descriptionText)) {
        Description description = new Description(descriptionText);
        vEvent.getProperties().add(description);
    }

    Integer status = eventValues.getAsInteger(CalendarContract.Events.STATUS);
    Long originalInstanceTime = eventValues.getAsLong(CalendarContract.Events.ORIGINAL_INSTANCE_TIME);
    if (status != null && status != CalendarContract.Events.STATUS_CANCELED && originalInstanceTime != null
            && originalInstanceTime > 0) {
        handleAddPropertiesForEditExceptionToRecurring(path, eventValues, vEvent);
    }

    if (status != null && status == CalendarContract.Events.STATUS_CONFIRMED)
        vEvent.getProperties().add(Status.VEVENT_CONFIRMED);
    else if (status != null && status == CalendarContract.Events.STATUS_CANCELED)
        handleAddPropertiesForDeletionExceptionToRecurring(path, eventValues, vEvent);
    else
        vEvent.getProperties().add(Status.VEVENT_TENTATIVE);

    Integer availability = eventValues.getAsInteger(CalendarContract.Events.AVAILABILITY);
    if (availability != null && availability == CalendarContract.Events.AVAILABILITY_BUSY)
        vEvent.getProperties().add(Transp.OPAQUE);
    else
        vEvent.getProperties().add(Transp.TRANSPARENT);

    Long dtStartMilliseconds = eventValues.getAsLong(CalendarContract.Events.DTSTART);
    if (dtStartMilliseconds == null)
        dtStartMilliseconds = eventValues.getAsLong(CalendarContract.Events.ORIGINAL_INSTANCE_TIME);

    if (dtStartMilliseconds != null) {
        DtStart dtStart = new DtStart(new Date(dtStartMilliseconds));
        String dtStartTZText = eventValues.getAsString(CalendarContract.Events.EVENT_TIMEZONE);

        if (dtStartTZText != null) {
            DateTime startDate = new DateTime(dtStartMilliseconds);
            TimeZone startTimeZone = registry.getTimeZone(dtStartTZText);
            startDate.setTimeZone(startTimeZone);

            dtStart = new DtStart(startDate);
        }

        vEvent.getProperties().add(dtStart);
    } else {
        Log.e(TAG, "no start date found on event");
        throw new InvalidComponentException("no start date found on event", false,
                CalDavConstants.CALDAV_NAMESPACE, path);
    }

    Long dtEndMilliseconds = eventValues.getAsLong(CalendarContract.Events.DTEND);
    if (dtEndMilliseconds != null && dtEndMilliseconds > 0) {
        DtEnd dtEnd = new DtEnd(new Date(dtEndMilliseconds));
        String dtStartTZText = eventValues.getAsString(CalendarContract.Events.EVENT_TIMEZONE);

        if (dtStartTZText != null) {
            DateTime endDate = new DateTime(dtEndMilliseconds);
            TimeZone endTimeZone = registry.getTimeZone(dtStartTZText);
            endDate.setTimeZone(endTimeZone);

            dtEnd = new DtEnd(endDate);
        }

        vEvent.getProperties().add(dtEnd);
    }

    String durationText = eventValues.getAsString(CalendarContract.Events.DURATION);
    if (StringUtils.isNotEmpty(durationText)) {
        Dur dur = new Dur(durationText);
        Duration duration = new Duration(dur);
        vEvent.getProperties().add(duration);
    }

    try {

        String rRuleText = eventValues.getAsString(CalendarContract.Events.RRULE);
        if (StringUtils.isNotEmpty(rRuleText)) {
            RRule rRule = new RRule(rRuleText);
            vEvent.getProperties().add(rRule);
        }

        String rDateText = eventValues.getAsString(CalendarContract.Events.RDATE);
        if (StringUtils.isNotEmpty(rDateText)) {
            RDate rDate = new RDate();
            rDate.setValue(rDateText);
            vEvent.getProperties().add(rDate);
        }

        String exRuleText = eventValues.getAsString(CalendarContract.Events.EXRULE);
        if (StringUtils.isNotEmpty(exRuleText)) {
            ExRule exRule = new ExRule();
            exRule.setValue(exRuleText);
            vEvent.getProperties().add(exRule);
        }

        String exDateText = eventValues.getAsString(CalendarContract.Events.EXDATE);
        if (StringUtils.isNotEmpty(exDateText)) {
            ExDate exDate = new ExDate();
            exDate.setValue(exDateText);
            vEvent.getProperties().add(exDate);
        }

    } catch (ParseException e) {
        Log.e(TAG, "caught exception while parsing recurrence rule stuff from event values", e);
        throw new InvalidComponentException(
                "caught exception while parsing recurrence rule stuff from event values", false,
                CalDavConstants.CALDAV_NAMESPACE, path, e);
    }

    calendar.getComponents().add(vEvent);
    Optional<String> eTag = Optional.fromNullable(eventValues.getAsString(CalendarContract.Events.SYNC_DATA1));

    return new ComponentETagPair<Calendar>(calendar, eTag);
}

From source file:com.chen.mail.browse.ConversationCursor.java

/**
 * Reset the cursor; this involves clearing out our cache map and resetting our various counts
 * The cursor should be reset whenever we get fresh data from the underlying cursor. The cache
 * is locked during the reset, which will block the UI, but for only a very short time
 * (estimated at a few ms, but we can profile this; remember that the cache will usually
 * be empty or have a few entries)//from  ww w .  j ava  2 s  .c om
 */
private void resetCursor(UnderlyingCursorWrapper newCursorWrapper) {
    synchronized (mCacheMapLock) {
        // Walk through the cache
        final Iterator<Map.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator();
        final long now = System.currentTimeMillis();
        while (iter.hasNext()) {
            Map.Entry<String, ContentValues> entry = iter.next();
            final ContentValues values = entry.getValue();
            final String key = entry.getKey();
            boolean withinTimeWindow = false;
            boolean removed = false;
            if (values != null) {
                Long updateTime = values.getAsLong(UPDATE_TIME_COLUMN);
                if (updateTime != null && ((now - updateTime) < REQUERY_ALLOWANCE_TIME)) {
                    LogUtils.d(LOG_TAG, "IN resetCursor, keep recent changes to %s", key);
                    withinTimeWindow = true;
                } else if (updateTime == null) {
                    LogUtils.e(LOG_TAG, "null updateTime from mCacheMap for key: %s", key);
                }
                if (values.containsKey(DELETED_COLUMN)) {
                    // Item is deleted locally AND deleted in the new cursor.
                    if (!newCursorWrapper.contains(key)) {
                        // Keep the deleted count up-to-date; remove the
                        // cache entry
                        mDeletedCount--;
                        removed = true;
                        LogUtils.d(LOG_TAG, "IN resetCursor, sDeletedCount decremented to: %d by %s",
                                mDeletedCount, key);
                    }
                }
            } else {
                LogUtils.e(LOG_TAG, "null ContentValues from mCacheMap for key: %s", key);
            }
            // Remove the entry if it was time for an update or the item was deleted by the user.
            if (!withinTimeWindow || removed) {
                iter.remove();
            }
        }

        // Swap cursor
        if (mUnderlyingCursor != null) {
            close();
        }
        mUnderlyingCursor = newCursorWrapper;

        mPosition = -1;
        mUnderlyingCursor.moveToPosition(mPosition);
        if (!mCursorObserverRegistered) {
            mUnderlyingCursor.registerContentObserver(mCursorObserver);
            mCursorObserverRegistered = true;

        }
        mRefreshRequired = false;

        // If the underlying cursor has received an update before we have gotten to this
        // point, we will want to make sure to refresh
        final boolean underlyingCursorUpdated = mUnderlyingCursor.isDataUpdated();
        mUnderlyingCursor.disableUpdateNotifications();
        if (underlyingCursorUpdated) {
            underlyingChanged();
        }
    }
    if (DEBUG)
        LogUtils.i(LOG_TAG, "OUT resetCursor, this=%s", this);
}

From source file:com.android.mail.browse.ConversationCursor.java

/**
 * Reset the cursor; this involves clearing out our cache map and resetting our various counts
 * The cursor should be reset whenever we get fresh data from the underlying cursor. The cache
 * is locked during the reset, which will block the UI, but for only a very short time
 * (estimated at a few ms, but we can profile this; remember that the cache will usually
 * be empty or have a few entries)/*from   w w w. j a va2  s.  c  o m*/
 */
private void resetCursor(UnderlyingCursorWrapper newCursorWrapper) {
    synchronized (mCacheMapLock) {
        // Walk through the cache
        final Iterator<Map.Entry<String, ContentValues>> iter = mCacheMap.entrySet().iterator();
        final long now = System.currentTimeMillis();
        while (iter.hasNext()) {
            Map.Entry<String, ContentValues> entry = iter.next();
            final ContentValues values = entry.getValue();
            final String key = entry.getKey();
            boolean withinTimeWindow = false;
            boolean removed = false;
            if (values != null) {
                Long updateTime = values.getAsLong(UPDATE_TIME_COLUMN);
                if (updateTime != null && ((now - updateTime) < REQUERY_ALLOWANCE_TIME)) {
                    LogUtils.d(LOG_TAG, "IN resetCursor, keep recent changes to %s", key);
                    withinTimeWindow = true;
                } else if (updateTime == null) {
                    LogUtils.e(LOG_TAG, "null updateTime from mCacheMap for key: %s", key);
                }
                if (values.containsKey(DELETED_COLUMN)) {
                    // Item is deleted locally AND deleted in the new cursor.
                    if (!newCursorWrapper.contains(key)) {
                        // Keep the deleted count up-to-date; remove the
                        // cache entry
                        mDeletedCount--;
                        removed = true;
                        LogUtils.i(LOG_TAG, "IN resetCursor, sDeletedCount decremented to: %d by %s",
                                mDeletedCount,
                                (LogUtils.isLoggable(LOG_TAG, LogUtils.DEBUG)) ? key : "[redacted]");
                    }
                }
            } else {
                LogUtils.e(LOG_TAG, "null ContentValues from mCacheMap for key: %s", key);
            }
            // Remove the entry if it was time for an update or the item was deleted by the user.
            if (!withinTimeWindow || removed) {
                iter.remove();
            }
        }

        // Swap cursor
        if (mUnderlyingCursor != null) {
            close();
        }
        mUnderlyingCursor = newCursorWrapper;

        mPosition = -1;
        mUnderlyingCursor.moveToPosition(mPosition);
        if (!mCursorObserverRegistered) {
            mUnderlyingCursor.registerContentObserver(mCursorObserver);
            mCursorObserverRegistered = true;

        }
        mRefreshRequired = false;

        // If the underlying cursor has received an update before we have gotten to this
        // point, we will want to make sure to refresh
        final boolean underlyingCursorUpdated = mUnderlyingCursor.isDataUpdated();
        mUnderlyingCursor.disableUpdateNotifications();
        if (underlyingCursorUpdated) {
            underlyingChanged();
        }
    }
    if (DEBUG)
        LogUtils.i(LOG_TAG, "OUT resetCursor, this=%s", this);
}

From source file:com.partypoker.poker.engagement.reach.EngagementReachAgent.java

/**
 * Called when a message download completes.
 * @param message message parameters./* w ww.  j  av  a  2 s  . c o  m*/
 */
void onMessageDownloaded(Bundle message) {
    /*
     * Get all campaigns from storage that matches this DLC identifier (manual push can have several
     * pushes for same DLC id).
     */
    String id = message.getString(INTENT_EXTRA_ID);
    if (id == null)
        return;
    Scanner scanner = mDB.getScanner(DLC_ID, id);
    for (ContentValues values : scanner) {
        /* Parse it */
        EngagementReachContent content = null;
        try {
            /* Parse and restore state */
            content = parseContentFromStorage(values);
            long localId = content.getLocalId();
            mPendingDLCs.remove(localId);
            boolean mustNotify = !content.isDlcCompleted() && (content.hasNotificationDLC()
                    || content instanceof com.microsoft.azure.engagement.reach.EngagementDataPush);

            /* Parse downloaded payload as JSON */
            String rawPayload = message.getString(INTENT_EXTRA_PAYLOAD);
            JSONObject payload = new JSONObject(rawPayload);
            content.setPayload(payload);

            /* Store it */
            ContentValues update = new ContentValues();
            update.put(PAYLOAD, rawPayload);
            mDB.update(localId, update);

            /* Cache is out of date, update it */
            mContentCache.put(localId, content);

            /* Start content if we were loading it */
            if (mState == State.LOADING && localId == mCurrentShownContentId)
                showContent(content);

            /* Notify if we were waiting for DLC to generate notification */
            else if (mustNotify && mInjectedParams.containsKey("{deviceid}"))
                notifyContent(content, false);
        } catch (Exception e) {
            /*
             * Delete content and send dropped feedback if possible depending on how much state we could
             * restore.
             */
            if (content == null) {
                Long oid = values.getAsLong(OID);
                if (oid != null)
                    delete(oid);
            } else
                content.dropContent(mContext);
        }
    }
    scanner.close();
}

From source file:com.ichi2.anki.provider.CardContentProvider.java

@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
    Timber.d("CardContentProvider.update");
    Collection col = CollectionHelper.getInstance().getCol(getContext());
    if (col == null) {
        return 0;
    }/* w w w.  j  a v a2  s.  co  m*/

    // Find out what data the user is requesting
    int match = sUriMatcher.match(uri);

    int updated = 0; // Number of updated entries (return value)
    switch (match) {
    case NOTES:
        throw new IllegalArgumentException("Not possible to update notes directly (only through data URI)");
    case NOTES_ID: {
        /* Direct access note details
         */
        Note currentNote = getNoteFromUri(uri, col);
        // the key of the ContentValues contains the column name
        // the value of the ContentValues contains the row value.
        Set<Map.Entry<String, Object>> valueSet = values.valueSet();
        for (Map.Entry<String, Object> entry : valueSet) {
            String key = entry.getKey();
            if (key.equals(FlashCardsContract.Note.FLDS)) {
                // Update FLDS
                Timber.d("CardContentProvider: flds update...");
                String newFldsEncoded = (String) entry.getValue();
                String[] flds = Utils.splitFields(newFldsEncoded);
                // Check that correct number of flds specified
                if (flds.length != currentNote.getFields().length) {
                    throw new IllegalArgumentException("Incorrect flds argument : " + newFldsEncoded);
                }
                // Update the note
                for (int idx = 0; idx < flds.length; idx++) {
                    currentNote.setField(idx, flds[idx]);
                }
                updated++;
            } else if (key.equals(FlashCardsContract.Note.TAGS)) {
                // Update tags
                Timber.d("CardContentProvider: tags update...");
                currentNote.setTagsFromStr((String) entry.getValue());
                updated++;
            } else {
                // Unsupported column
                throw new IllegalArgumentException("Unsupported column: " + key);
            }
        }
        Timber.d("CardContentProvider: Saving note...");
        currentNote.flush();
        break;
    }
    case NOTES_ID_CARDS:
        // TODO: To be implemented
        throw new UnsupportedOperationException("Not yet implemented");
        //                break;
    case NOTES_ID_CARDS_ORD: {
        Card currentCard = getCardFromUri(uri, col);
        boolean isDeckUpdate = false;
        long did = -1;
        // the key of the ContentValues contains the column name
        // the value of the ContentValues contains the row value.
        Set<Map.Entry<String, Object>> valueSet = values.valueSet();
        for (Map.Entry<String, Object> entry : valueSet) {
            // Only updates on deck id is supported
            String key = entry.getKey();
            isDeckUpdate = key.equals(FlashCardsContract.Card.DECK_ID);
            did = values.getAsLong(key);
        }

        /* now update the card
         */
        if ((isDeckUpdate) && (did >= 0)) {
            Timber.d("CardContentProvider: Moving card to other deck...");
            col.getDecks().flush();
            currentCard.setDid(did);
            currentCard.flush();
            updated++;
        } else {
            // User tries an operation that is not (yet?) supported.
            throw new IllegalArgumentException("Currently only updates of decks are supported");
        }
        break;
    }
    case MODELS:
        throw new IllegalArgumentException("Cannot update models in bulk");
    case MODELS_ID:
        // Get the input parameters
        String newModelName = values.getAsString(FlashCardsContract.Model.NAME);
        String newCss = values.getAsString(FlashCardsContract.Model.CSS);
        String newDid = values.getAsString(FlashCardsContract.Model.DECK_ID);
        String newFieldList = values.getAsString(FlashCardsContract.Model.FIELD_NAMES);
        if (newFieldList != null) {
            // Changing the field names would require a full-sync
            throw new IllegalArgumentException("Field names cannot be changed via provider");
        }
        // Get the original note JSON
        JSONObject model = col.getModels().get(getModelIdFromUri(uri, col));
        try {
            // Update model name and/or css
            if (newModelName != null) {
                model.put("name", newModelName);
                updated++;
            }
            if (newCss != null) {
                model.put("css", newCss);
                updated++;
            }
            if (newDid != null) {
                model.put("did", newDid);
                updated++;
            }
            col.getModels().save(model);
        } catch (JSONException e) {
            Timber.e(e, "JSONException updating model");
        }
        break;
    case MODELS_ID_TEMPLATES:
        throw new IllegalArgumentException("Cannot update templates in bulk");
    case MODELS_ID_TEMPLATES_ID:
        Long mid = values.getAsLong(CardTemplate.MODEL_ID);
        Integer ord = values.getAsInteger(CardTemplate.ORD);
        String name = values.getAsString(CardTemplate.NAME);
        String qfmt = values.getAsString(CardTemplate.QUESTION_FORMAT);
        String afmt = values.getAsString(CardTemplate.ANSWER_FORMAT);
        String bqfmt = values.getAsString(CardTemplate.BROWSER_QUESTION_FORMAT);
        String bafmt = values.getAsString(CardTemplate.BROWSER_ANSWER_FORMAT);
        // Throw exception if read-only fields are included
        if (mid != null || ord != null) {
            throw new IllegalArgumentException("Can update mid or ord");
        }
        // Update the model
        try {
            Integer templateOrd = Integer.parseInt(uri.getLastPathSegment());
            JSONObject existingModel = col.getModels().get(getModelIdFromUri(uri, col));
            JSONArray templates = existingModel.getJSONArray("tmpls");
            JSONObject template = templates.getJSONObject(templateOrd);
            if (name != null) {
                template.put("name", name);
                updated++;
            }
            if (qfmt != null) {
                template.put("qfmt", qfmt);
                updated++;
            }
            if (afmt != null) {
                template.put("afmt", afmt);
                updated++;
            }
            if (bqfmt != null) {
                template.put("bqfmt", bqfmt);
                updated++;
            }
            if (bafmt != null) {
                template.put("bafmt", bafmt);
                updated++;
            }
            // Save the model
            templates.put(templateOrd, template);
            existingModel.put("tmpls", templates);
            col.getModels().save(existingModel, true);
        } catch (JSONException e) {
            throw new IllegalArgumentException("Model is malformed", e);
        }
        break;
    case SCHEDULE: {
        Set<Map.Entry<String, Object>> valueSet = values.valueSet();
        int cardOrd = -1;
        long noteID = -1;
        int ease = -1;
        long timeTaken = -1;
        for (Map.Entry<String, Object> entry : valueSet) {
            String key = entry.getKey();

            if (key.equals(FlashCardsContract.ReviewInfo.NOTE_ID)) {
                noteID = values.getAsLong(key);
            } else if (key.equals(FlashCardsContract.ReviewInfo.CARD_ORD)) {
                cardOrd = values.getAsInteger(key);
            } else if (key.equals(FlashCardsContract.ReviewInfo.EASE)) {
                ease = values.getAsInteger(key);
            } else if (key.equals(FlashCardsContract.ReviewInfo.TIME_TAKEN)) {
                timeTaken = values.getAsLong(key);
            }
        }
        if (cardOrd != -1 && noteID != -1) {
            Card cardToAnswer = getCard(noteID, cardOrd, col);
            if (cardToAnswer != null) {
                answerCard(col, col.getSched(), cardToAnswer, ease, timeTaken);
                updated++;
            } else {
                Timber.e(
                        "Requested card with noteId %d and cardOrd %d was not found. Either the provided "
                                + "noteId/cardOrd were wrong or the card has been deleted in the meantime.",
                        noteID, cardOrd);
            }
        }
        break;
    }
    case DECKS:
        throw new IllegalArgumentException("Can't update decks in bulk");
    case DECKS_ID:
        throw new UnsupportedOperationException("Not yet implemented");
    case DECK_SELECTED: {
        Set<Map.Entry<String, Object>> valueSet = values.valueSet();
        for (Map.Entry<String, Object> entry : valueSet) {
            String key = entry.getKey();
            if (key.equals(FlashCardsContract.Deck.DECK_ID)) {
                long deckId = values.getAsLong(key);
                if (selectDeckWithCheck(col, deckId)) {
                    updated++;
                }
            }
        }
        break;
    }
    default:
        // Unknown URI type
        throw new IllegalArgumentException("uri " + uri + " is not supported");
    }
    return updated;
}

From source file:com.attentec.AttentecService.java

/**
 * Parse one user from JSONObject and save to database.
 * @param user the JSONObject to parse/*w w w .jav a  2  s.  co m*/
 * @param username the username of ourselves
 * @return which userid whas updated
 * @throws JSONException if parsing failed
 */
@SuppressWarnings("unchecked")
private String parseJSONUser(final JSONObject user, final String username) throws JSONException {
    //Log.d(TAG, "parsing JSON user");
    ContentValues cv = new ContentValues();
    String updated = new String();
    //go over all fields
    Iterator<String> it = user.keys();
    boolean isSelf = false;
    while (it.hasNext()) {
        String key = it.next();
        String value = null;
        try {
            value = user.getString(key);
        } catch (JSONException e) {
            Log.e(TAG, "JSONException user field: " + key);
            throw e;
        }

        if (key.equals("id")) {
            key = "_id";
            updated = value;
        } else if (key.equals("photo_url")) {
            //check if there is a valid photo
            String newPhotoUpdatedAt = null;
            try {
                newPhotoUpdatedAt = cleanDate(user.getString("photo_updated_at"));
            } catch (JSONException e) {
                Log.e(TAG, "Could not parse photo_updated_at.");
                continue;
            }

            if (newPhotoUpdatedAt == null) {
                //no photo exists, so we don't need to save one
                //Log.d(TAG, "No photo exists");
                continue;
            }

            Long userId = null;
            try {
                userId = Long.parseLong(user.getString("id"));
            } catch (NumberFormatException e) {
                Log.e(TAG, "Could not parse user id from server.");
                continue;
            } catch (JSONException e3) {
                Log.e(TAG, "Could not parse user id from server.");
                continue;
            }

            //check if the user already exists
            if (!dbh.userExists(userId)) {
                //this is a new user, we can get a new image
                try {
                    cv.put(DatabaseAdapter.KEY_PHOTO, getImage(value));
                } catch (GetImageException e) {
                    Log.e(TAG, "Could not get image: " + e.getMessage());
                    continue;
                }
            }

            //we want to check if this photo is newer than the one we have now

            //parse the date
            dfm.setLenient(true);
            Date newTimestamp = new Date();
            try {
                newTimestamp = dfm.parse(newPhotoUpdatedAt);
            } catch (ParseException e1) {
                Log.e(TAG, "Could not parse newPhotoUpdatedAt: " + newPhotoUpdatedAt);
                continue;
            }

            String oldPhotoUpdatedAt = dbh.getContactPhotoUpdatedAt(userId);

            Date oldTimestamp = new Date();
            if (oldPhotoUpdatedAt != null) {
                //parse the date
                try {
                    oldTimestamp = (dfm.parse(oldPhotoUpdatedAt));
                } catch (ParseException e) {
                    Log.e(TAG, "Could not parse oldPhotoUpdatedAt: " + oldPhotoUpdatedAt);
                }
            }

            if ((oldTimestamp.getTime() != newTimestamp.getTime())) {
                Log.d(TAG, "There is a new photo, downloading...");
                try {
                    cv.put(DatabaseAdapter.KEY_PHOTO, getImage(user.get("photo_url").toString()));
                } catch (JSONException e) {
                    Log.e(TAG, "Could not parse photo_url.");
                } catch (GetImageException e) {
                    Log.e(TAG, "Could not get image: " + e.getMessage());
                }
            }
        } else if (key.equals("username") && value.equals(username)) {
            //save that this is ourself, we don't want to save ourselves
            isSelf = true;
            updated = null;
            break;
        } else if (key.equals(DatabaseAdapter.KEY_LOCATION_UPDATED_AT)
                || key.equals(DatabaseAdapter.KEY_CONNECTED_AT)
                || key.equals(DatabaseAdapter.KEY_PHOTO_UPDATED_AT)) {
            value = cleanDate(value);
        }

        if (key != "photo_url") {
            cv.put(key, value);
        }
    }

    //check if we are ourselves
    if (!isSelf) {
        //Log.d(TAG, "Saving user: " + cv.toString());
        Long existingrowId = cv.getAsLong(DatabaseAdapter.KEY_ROWID);
        cv.remove("photo_url");
        if (!dbh.userExists(existingrowId)) {
            //save the user to the database
            dbh.addUser(cv);
        } else {
            //update the user in the database
            dbh.updateUser(cv, existingrowId);
        }
    }
    return updated;
}

From source file:edu.stanford.mobisocial.dungbeetle.DungBeetleContentProvider.java

/**
 * Inserts a message locally that has been received from some agent,
 * typically from a remote device./*from  ww  w .  j  a  v  a 2s  .c  o m*/
 */
@Override
public Uri insert(Uri uri, ContentValues values) {
    ContentResolver resolver = getContext().getContentResolver();
    if (DBG)
        Log.i(TAG, "Inserting at uri: " + uri + ", " + values);

    final String appId = getCallingActivityId();
    if (appId == null) {
        Log.d(TAG, "No AppId for calling activity. Ignoring query.");
        return null;
    }

    List<String> segs = uri.getPathSegments();
    if (match(uri, "feeds", "me")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }

        long objId = mHelper.addToFeed(appId, "friend", values);
        Uri objUri = DbObject.uriForObj(objId);
        resolver.notifyChange(Feed.uriForName("me"), null);
        resolver.notifyChange(Feed.uriForName("friend"), null);
        resolver.notifyChange(objUri, null);
        return objUri;
    } else if (match(uri, "feeds", ".+")) {
        String feedName = segs.get(1);
        String type = values.getAsString(DbObject.TYPE);
        try {
            JSONObject json = new JSONObject(values.getAsString(DbObject.JSON));
            String objHash = null;
            if (feedName.contains(":")) {
                String[] parts = feedName.split(":");
                feedName = parts[0];
                objHash = parts[1];
            }
            if (objHash != null) {
                json.put(DbObjects.TARGET_HASH, Long.parseLong(objHash));
                json.put(DbObjects.TARGET_RELATION, DbRelation.RELATION_PARENT);
                values.put(DbObject.JSON, json.toString());
            }

            String appAuthority = appId;
            if (SUPER_APP_ID.equals(appId)) {
                if (AppObj.TYPE.equals(type)) {
                    if (json.has(AppObj.ANDROID_PACKAGE_NAME)) {
                        appAuthority = json.getString(AppObj.ANDROID_PACKAGE_NAME);
                    }
                }
            }

            long objId = mHelper.addToFeed(appAuthority, feedName, values);
            Uri objUri = DbObject.uriForObj(objId);
            resolver.notifyChange(objUri, null);
            notifyDependencies(mHelper, resolver, segs.get(1));
            if (DBG)
                Log.d(TAG, "just inserted " + values.getAsString(DbObject.JSON));
            return objUri;
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "out")) {
        try {
            JSONObject obj = new JSONObject(values.getAsString("json"));
            long objId = mHelper.addToOutgoing(appId, values.getAsString(DbObject.DESTINATION),
                    values.getAsString(DbObject.TYPE), obj);
            resolver.notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
            return DbObject.uriForObj(objId);
        } catch (JSONException e) {
            return null;
        }
    } else if (match(uri, "contacts")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertContact(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "subscribers")) {
        // Question: Should this be restricted?
        // if(!appId.equals(SUPER_APP_ID)) return null;
        long id = mHelper.insertSubscriber(values);
        resolver.notifyChange(Uri.parse(CONTENT_URI + "/subscribers"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "groups")) {
        if (!appId.equals(SUPER_APP_ID))
            return null;
        long id = mHelper.insertGroup(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        return uriWithId(uri, id);
    } else if (match(uri, "group_members")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        long id = mHelper.insertGroupMember(values);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"), null);
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"), null);
        return uriWithId(uri, id);
    }

    else if (match(uri, "group_invitations")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        String groupName = values.getAsString(InviteToGroupObj.GROUP_NAME);
        Uri dynUpdateUri = Uri.parse(values.getAsString(InviteToGroupObj.DYN_UPDATE_URI));
        long gid = values.getAsLong("groupId");
        SQLiteDatabase db = mHelper.getWritableDatabase();
        mHelper.addToOutgoing(db, appId, values.getAsString(InviteToGroupObj.PARTICIPANTS),
                InviteToGroupObj.TYPE, InviteToGroupObj.json(groupName, dynUpdateUri));
        getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/out"), null);
        return uriWithId(uri, gid);
    }

    else if (match(uri, "dynamic_groups")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        Uri gUri = Uri.parse(values.getAsString("uri"));
        GroupProviders.GroupProvider gp = GroupProviders.forUri(gUri);
        String feedName = gp.feedName(gUri);
        Maybe<Group> mg = mHelper.groupByFeedName(feedName);
        long id = -1;
        try {
            Group g = mg.get();
            id = g.id;
        } catch (Maybe.NoValError e) {
            ContentValues cv = new ContentValues();
            cv.put(Group.NAME, gp.groupName(gUri));
            cv.put(Group.FEED_NAME, feedName);
            cv.put(Group.DYN_UPDATE_URI, gUri.toString());

            String table = DbObject.TABLE;
            String[] columns = new String[] { DbObject.FEED_NAME };
            String selection = DbObject.CHILD_FEED_NAME + " = ?";
            String[] selectionArgs = new String[] { feedName };
            Cursor parent = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, null,
                    null, null);
            try {
                if (parent.moveToFirst()) {
                    String parentName = parent.getString(0);
                    table = Group.TABLE;
                    columns = new String[] { Group._ID };
                    selection = Group.FEED_NAME + " = ?";
                    selectionArgs = new String[] { parentName };

                    Cursor parent2 = mHelper.getReadableDatabase().query(table, columns, selection,
                            selectionArgs, null, null, null);
                    try {
                        if (parent2.moveToFirst()) {
                            cv.put(Group.PARENT_FEED_ID, parent2.getLong(0));
                        } else {
                            Log.e(TAG, "Parent feed found but no id for " + parentName);
                        }
                    } finally {
                        parent2.close();
                    }
                } else {
                    Log.w(TAG, "No parent feed for " + feedName);
                }
            } finally {
                parent.close();
            }
            id = mHelper.insertGroup(cv);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/dynamic_groups"), null);
            getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/groups"), null);
        }
        return uriWithId(uri, id);
    }

    else if (match(uri, "dynamic_group_member")) {
        if (!appId.equals(SUPER_APP_ID)) {
            return null;
        }
        SQLiteDatabase db = mHelper.getWritableDatabase();
        db.beginTransaction();
        try {
            ContentValues cv = new ContentValues();
            String pubKeyStr = values.getAsString(Contact.PUBLIC_KEY);
            RSAPublicKey k = RSACrypto.publicKeyFromString(pubKeyStr);
            String personId = mIdent.personIdForPublicKey(k);
            if (!personId.equals(mIdent.userPersonId())) {
                cv.put(Contact.PUBLIC_KEY, values.getAsString(Contact.PUBLIC_KEY));
                cv.put(Contact.NAME, values.getAsString(Contact.NAME));
                cv.put(Contact.EMAIL, values.getAsString(Contact.EMAIL));
                if (values.getAsString(Contact.PICTURE) != null) {
                    cv.put(Contact.PICTURE, values.getAsByteArray(Contact.PICTURE));
                }

                long cid = -1;
                Contact contact = mHelper.contactForPersonId(personId).otherwise(Contact.NA());
                if (contact.id > -1) {
                    cid = contact.id;
                } else {
                    cid = mHelper.insertContact(db, cv);
                }

                if (cid > -1) {

                    ContentValues gv = new ContentValues();
                    gv.put(GroupMember.GLOBAL_CONTACT_ID, values.getAsString(GroupMember.GLOBAL_CONTACT_ID));
                    gv.put(GroupMember.GROUP_ID, values.getAsLong(GroupMember.GROUP_ID));
                    gv.put(GroupMember.CONTACT_ID, cid);
                    mHelper.insertGroupMember(db, gv);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_members"),
                            null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/contacts"), null);
                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/group_contacts"),
                            null);

                    // Add subscription to this private group feed
                    ContentValues sv = new ContentValues();
                    sv = new ContentValues();
                    sv.put(Subscriber.CONTACT_ID, cid);
                    sv.put(Subscriber.FEED_NAME, values.getAsString(Group.FEED_NAME));
                    mHelper.insertSubscriber(db, sv);

                    ContentValues xv = new ContentValues();
                    xv.put(Subscriber.CONTACT_ID, cid);
                    xv.put(Subscriber.FEED_NAME, "friend");
                    mHelper.insertSubscriber(db, xv);

                    getContext().getContentResolver().notifyChange(Uri.parse(CONTENT_URI + "/subscribers"),
                            null);

                    db.setTransactionSuccessful();
                }
                return uriWithId(uri, cid);
            } else {
                Log.i(TAG, "Omitting self.");
                return uriWithId(uri, Contact.MY_ID);
            }
        } finally {
            db.endTransaction();
        }
    } else {
        Log.e(TAG, "Failed to insert into " + uri);
        return null;
    }
}