Example usage for android.content ContentResolver update

List of usage examples for android.content ContentResolver update

Introduction

In this page you can find the example usage for android.content ContentResolver update.

Prototype

public final int update(@RequiresPermission.Write @NonNull Uri uri, @Nullable ContentValues values,
        @Nullable String where, @Nullable String[] selectionArgs) 

Source Link

Document

Update row(s) in a content URI.

Usage

From source file:com.hhunj.hhudata.ForegroundService.java

private String updatedb(List<SearchBookContentsResult> items) {

    String sMessage = "";
    ContentResolver resolver = getApplicationContext().getContentResolver();

    ContentValues values = new ContentValues();

    for (int i = 0; i < items.size(); i++) {

        SearchBookContentsResult res = items.get(i);
        if (res == null)
            continue;
        long stationid = Long.parseLong(res.getPageNumber());

        values.put(NotePad.Notes.TITLE, res.getName());
        values.put(NotePad.Notes.NOTE, "");

        values.put(NotePad.Notes.LONGITUTE, 108.0);
        values.put(NotePad.Notes.LATITUDE, 32.0);
        values.put(NotePad.Notes.SPEED, 55);
        values.put(NotePad.Notes.ALTITUDE, 55);

        values.put(NotePad.Notes.CREATEDDATE, res.getRectime().getTime());

        values.put(NotePad.Notes._ID, stationid);// id

        Uri urlNote = NotePad.Notes.CONTENT_URI;

        Uri myUri = ContentUris.withAppendedId(NotePad.Notes.CONTENT_URI, stationid);

        //?????//from w  ww .  jav a 2 s .  c o m
        Cursor cur = resolver.query(myUri, NotePad.Notes.PROJECTION, null, null, null);
        if (cur == null) {
            // 
        }
        if (cur != null && cur.moveToFirst()) {
            long id = cur.getLong(NotePad.Notes._ID_COLUMN);
            Date oldtime = new Date(cur.getLong(cur.getColumnIndex(NotePad.Notes.CREATEDDATE)));
            boolean oldalarm = (cur.getInt(NotePad.Notes.ALARM_COLUMN) == 0) ? false : true;

            long dif = (res.getRectime().getTime() - oldtime.getTime()) / (60 * 1000);

            // 
            dif = ((new Date()).getTime() - oldtime.getTime()) / (60 * 1000);
            boolean newalarm = false;//
            if (dif > m_alamspan) {
                // ...
                if (oldalarm == false) {
                    Log.w(TAG, "over time err--------");
                    // String phoneNumber ="13338620269";
                    sMessage += "---" + id + "---";
                    newalarm = true;
                } else {
                    newalarm = true;
                }

            }

            values.put(NotePad.Notes.ALARM, newalarm);
            int count = resolver.update(myUri, values, null, null);
            if (count == 0) {

            }

        } else {
            values.put(NotePad.Notes.ALARM, false);
            try {
                myUri = resolver.insert(urlNote, values);
            } catch (IllegalArgumentException e) {
                throw e;
            } catch (SQLException e2) {
                int aa = 0;
                throw e2;
            }
        }
    }
    return sMessage;
}

From source file:com.akop.bach.parser.XboxLiveParser.java

private void parseMessages(XboxLiveAccount account) throws IOException, ParserException {
    long started = System.currentTimeMillis();

    String token = getVToken(String.format(URL_VTOKEN_MESSAGES, mLocale));

    String url = String.format(URL_JSON_MESSAGE_LIST, mLocale);

    List<NameValuePair> inputs = new ArrayList<NameValuePair>(3);
    addValue(inputs, "__RequestVerificationToken", token);

    String page = getResponse(url, inputs, true);
    JSONObject data = getXboxJsonObject(page);

    if (data == null)
        throw new ParserException(mContext, R.string.error_message_retrieval);

    JSONArray messages = data.optJSONArray("Messages");

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Message page fetch", started);

    long updated = started;
    boolean changed = false;
    String uid;/*from   ww  w . j  a  va  2 s .com*/
    ContentResolver cr = mContext.getContentResolver();
    Cursor c;
    ContentValues cv;
    List<ContentValues> newCvs = new ArrayList<ContentValues>();
    final String[] columns = new String[] { Messages._ID, Messages.IS_READ };

    for (int i = 0, n = messages.length(); i < n; i++) {
        JSONObject message = messages.optJSONObject(i);

        if (message == null || (uid = message.optString("Id")) == null)
            continue;

        int isRead = message.optBoolean("HasBeenRead") ? 1 : 0;

        c = cr.query(Messages.CONTENT_URI, columns,
                Messages.ACCOUNT_ID + "=" + account.getId() + " AND " + Messages.UID + "=" + uid, null, null);

        try {
            if (c != null && c.moveToFirst()) {
                String gamerpic = message.optString("GamerPic");

                // Message already in system
                cv = new ContentValues(5);
                cv.put(Messages.IS_READ, isRead);
                cv.put(Messages.DELETE_MARKER, updated);
                cv.put(Messages.GAMERPIC, gamerpic);

                changed = true;
                cr.update(Messages.CONTENT_URI, cv, Messages._ID + "=" + c.getLong(0), null);
            } else {
                long sent = parseTicks(message.optString("SentTime"));

                String body = message.optString("Excerpt", "");
                String sender = message.optString("From", "");
                String gamerpic = message.optString("GamerPic");

                int type = XboxLive.MESSAGE_TEXT;
                if (message.optBoolean("HasImage"))
                    type = XboxLive.MESSAGE_OTHER;
                if (message.optBoolean("HasVoice"))
                    type = XboxLive.MESSAGE_VOICE;

                // New message
                cv = new ContentValues(10);
                cv.put(Messages.ACCOUNT_ID, account.getId());
                cv.put(Messages.SENDER, sender);
                cv.put(Messages.GAMERPIC, gamerpic);
                cv.put(Messages.UID, uid);
                cv.put(Messages.IS_READ, isRead);
                cv.put(Messages.IS_DIRTY, 1);
                cv.put(Messages.TYPE, type);
                cv.put(Messages.SENT, sent);
                cv.put(Messages.DELETE_MARKER, updated);
                cv.put(Messages.BODY, htmlDecode(body));

                newCvs.add(cv);
            }
        } finally {
            if (c != null)
                c.close();
        }
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Message list processing", started);

    if (newCvs.size() > 0) {
        changed = true;

        ContentValues[] cvs = new ContentValues[newCvs.size()];
        newCvs.toArray(cvs);

        cr.bulkInsert(Messages.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Message list insertion", started);
    }

    int deleted = cr.delete(Messages.CONTENT_URI,
            Messages.DELETE_MARKER + "!=" + updated + " AND " + Messages.ACCOUNT_ID + "=" + account.getId(),
            null);

    account.refresh(Preferences.get(mContext));
    account.setLastMessageUpdate(System.currentTimeMillis());
    account.save(Preferences.get(mContext));

    if (changed || deleted > 0)
        cr.notifyChange(Messages.CONTENT_URI, null);
}

From source file:com.akop.bach.parser.PsnEuParser.java

@SuppressLint("DefaultLocale")
@Override//from  w w  w  . j a  va 2s  .  c o  m
protected void parseFriends(PsnAccount account) throws ParserException, IOException {
    synchronized (PsnEuParser.class) {
        ContentResolver cr = mContext.getContentResolver();
        ContentValues cv;
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);
        final long accountId = account.getId();

        int rowsInserted = 0;
        int rowsUpdated = 0;
        int rowsDeleted = 0;

        long updated = System.currentTimeMillis();
        long started = updated;

        // Handle pending requests
        String page = getResponse(URL_FRIENDS);

        Matcher m;
        Matcher friendMatcher = PATTERN_FRIENDS_PENDING.matcher(page);

        while (friendMatcher.find()) {
            String onlineId = htmlDecode(friendMatcher.group(1));
            Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
                    Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                    new String[] { onlineId }, null);

            long friendId = -1;

            try {
                if (c != null && c.moveToFirst())
                    friendId = c.getLong(0);
            } finally {
                if (c != null)
                    c.close();
            }

            cv = new ContentValues(15);

            cv.put(Friends.DELETE_MARKER, updated);
            cv.put(Friends.ONLINE_STATUS, PSN.STATUS_PENDING);

            if (friendId < 0) {
                // New
                cv.put(Friends.ONLINE_ID, onlineId);
                cv.put(Friends.ACCOUNT_ID, accountId);
                cv.put(Friends.PROGRESS, 0);
                cv.putNull(Friends.ICON_URL);
                cv.put(Friends.LEVEL, 0);
                cv.put(Friends.TROPHIES_PLATINUM, 0);
                cv.put(Friends.TROPHIES_GOLD, 0);
                cv.put(Friends.TROPHIES_SILVER, 0);
                cv.put(Friends.TROPHIES_BRONZE, 0);
                cv.putNull(Friends.PLAYING);
                cv.put(Friends.LAST_UPDATED, 0);

                newCvs.add(cv);
            } else {
                cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);

                rowsUpdated++;
            }
        }

        // Handle rest of friends
        page = getResponse(URL_FRIENDS_AJAX);
        friendMatcher = PATTERN_FRIENDS.matcher(page);

        while (friendMatcher.find()) {
            String friendData = friendMatcher.group(1);

            String onlineId;
            if (!(m = PATTERN_FRIEND_ONLINE_ID.matcher(friendData)).find())
                continue;

            onlineId = htmlDecode(m.group(1));

            int level = 0;
            if ((m = PATTERN_FRIEND_LEVEL.matcher(friendData)).find())
                level = Integer.parseInt(m.group(1));

            String iconUrl = null;
            if ((m = PATTERN_FRIEND_AVATAR.matcher(friendData)).find())
                iconUrl = getLargeAvatarIcon(resolveImageUrl(URL_FRIENDS_AJAX, m.group(1)));

            String comment = null;
            if ((m = PATTERN_FRIEND_COMMENT.matcher(friendData)).find()) {
                comment = htmlDecode(m.group(1));
                if (comment != null && comment.equals("null"))
                    comment = null;
            }

            int memberType = PSN.MEMBER_TYPE_FREE;
            if ((m = PATTERN_FRIEND_IS_PLUS.matcher(friendData)).find()
                    && m.group(1).equalsIgnoreCase("true")) {
                memberType = PSN.MEMBER_TYPE_PLUS;
            }

            int bronze = 0;
            int silver = 0;
            int gold = 0;
            int platinum = 0;

            m = PATTERN_FRIEND_TROPHY.matcher(friendData);
            while (m.find()) {
                String type = m.group(1).toLowerCase();
                if ("bronze".equals(type))
                    bronze = Integer.parseInt(m.group(2));
                else if ("silver".equals(type))
                    silver = Integer.parseInt(m.group(2));
                else if ("gold".equals(type))
                    gold = Integer.parseInt(m.group(2));
                else if ("platinum".equals(type))
                    platinum = Integer.parseInt(m.group(2));
            }

            boolean inGame = false;
            int status = PSN.STATUS_OTHER;
            if ((m = PATTERN_FRIEND_STATUS.matcher(friendData)).find()) {
                String presence = m.group(1).toLowerCase();
                if (presence.equals("offline"))
                    status = PSN.STATUS_OFFLINE;
                else if (presence.equals("online"))
                    status = PSN.STATUS_ONLINE;
                else if (presence.equals("online-ingame")) {
                    status = PSN.STATUS_ONLINE;
                    inGame = true;
                } else if (presence.equals("online-away"))
                    status = PSN.STATUS_AWAY;
                else if (presence.equals("online-ingame-away")) {
                    status = PSN.STATUS_AWAY;
                    inGame = true;
                } else if (presence.equals("pending"))
                    status = PSN.STATUS_PENDING;
            }

            String playing = null;
            if ((m = PATTERN_FRIEND_PLAYING.matcher(friendData)).find()) {
                String activity = htmlDecode(m.group(1)).trim();

                if (activity != null && activity.length() > 0) {
                    if (inGame)
                        playing = mContext.getString(R.string.playing_f, activity);
                    else
                        playing = activity;
                }
            }

            Cursor c = cr.query(Friends.CONTENT_URI, FRIEND_ID_PROJECTION,
                    Friends.ACCOUNT_ID + "=" + account.getId() + " AND " + Friends.ONLINE_ID + "=?",
                    new String[] { onlineId }, null);

            long friendId = -1;

            try {
                if (c != null && c.moveToFirst())
                    friendId = c.getLong(0);
            } finally {
                if (c != null)
                    c.close();
            }

            cv = new ContentValues(15);

            cv.put(Friends.ICON_URL, iconUrl);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.MEMBER_TYPE, memberType);
            cv.put(Friends.COMMENT, comment);
            cv.put(Friends.LEVEL, level);
            cv.put(Friends.ONLINE_STATUS, status);
            cv.put(Friends.TROPHIES_PLATINUM, platinum);
            cv.put(Friends.TROPHIES_GOLD, gold);
            cv.put(Friends.TROPHIES_SILVER, silver);
            cv.put(Friends.TROPHIES_BRONZE, bronze);
            cv.put(Friends.PLAYING, playing);
            cv.put(Friends.DELETE_MARKER, updated);

            if (friendId < 0) {
                // New
                cv.put(Friends.ONLINE_ID, onlineId);
                cv.put(Friends.ACCOUNT_ID, accountId);
                cv.put(Friends.PROGRESS, 0);
                cv.put(Friends.LAST_UPDATED, 0);

                newCvs.add(cv);
            } else {
                cr.update(ContentUris.withAppendedId(Friends.CONTENT_URI, friendId), cv, null, null);

                rowsUpdated++;
            }
        }

        // Remove friends
        rowsDeleted = cr.delete(Friends.CONTENT_URI,
                Friends.ACCOUNT_ID + "=" + accountId + " AND " + Friends.DELETE_MARKER + "!=" + updated, null);

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);

            rowsInserted = cr.bulkInsert(Friends.CONTENT_URI, cvs);
        }

        account.refresh(Preferences.get(mContext));
        account.setLastFriendUpdate(System.currentTimeMillis());
        account.save(Preferences.get(mContext));

        cr.notifyChange(Friends.CONTENT_URI, null);

        if (App.getConfig().logToConsole())
            started = displayTimeTaken("Friend page processing [I:" + rowsInserted + ";U:" + rowsUpdated + ";D:"
                    + rowsDeleted + "]", started);
    }
}

From source file:org.totschnig.myexpenses.MyApplication.java

/**
 * 1.check if a planner is configured. If no, nothing to do 2.check if the
 * configured planner exists on the device 2.1 if yes go through all events
 * and look for them based on UUID added to description recreate events that
 * we did not find (2.2 if no, user should have been asked to select a target
 * calendar where we will store the recreated events)
 *
 * @return Result with success true//www. ja va 2 s .  co  m
 */
public Result restorePlanner() {
    ContentResolver cr = getContentResolver();
    String TAG = "restorePlanner";
    String calendarId = PrefKey.PLANNER_CALENDAR_ID.getString("-1");
    String calendarPath = PrefKey.PLANNER_CALENDAR_PATH.getString("");
    Log.d(TAG, String.format("restore plans to calendar with id %s and path %s", calendarId, calendarPath));
    int restoredPlansCount = 0;
    if (!(calendarId.equals("-1") || calendarPath.equals(""))) {
        Cursor c = cr.query(Calendars.CONTENT_URI, new String[] { Calendars._ID },
                CALENDAR_FULL_PATH_PROJECTION + " = ?", new String[] { calendarPath }, null);
        if (c != null) {
            if (c.moveToFirst()) {
                mPlannerCalendarId = c.getString(0);
                Log.d(TAG, String.format("restorePlaner: found calendar with id %s", mPlannerCalendarId));
                PrefKey.PLANNER_CALENDAR_ID.putString(mPlannerCalendarId);
                ContentValues planValues = new ContentValues(), eventValues = new ContentValues();
                eventValues.put(Events.CALENDAR_ID, Long.parseLong(mPlannerCalendarId));
                Cursor planCursor = cr.query(Template.CONTENT_URI,
                        new String[] { DatabaseConstants.KEY_ROWID, DatabaseConstants.KEY_PLANID,
                                DatabaseConstants.KEY_UUID },
                        DatabaseConstants.KEY_PLANID + " IS NOT null", null, null);
                if (planCursor != null) {
                    if (planCursor.moveToFirst()) {
                        do {
                            long templateId = planCursor.getLong(0);
                            long oldPlanId = planCursor.getLong(1);
                            String uuid = planCursor.getString(2);
                            Cursor eventCursor = cr.query(Events.CONTENT_URI, new String[] { Events._ID },
                                    Events.CALENDAR_ID + " = ? AND " + Events.DESCRIPTION + " LIKE ?",
                                    new String[] { mPlannerCalendarId, "%" + uuid + "%" }, null);
                            if (eventCursor != null) {
                                if (eventCursor.moveToFirst()) {
                                    long newPlanId = eventCursor.getLong(0);
                                    Log.d(TAG,
                                            String.format(
                                                    "Looking for event with uuid %s: found id %d. "
                                                            + "Original event had id %d",
                                                    uuid, newPlanId, oldPlanId));
                                    if (newPlanId != oldPlanId) {
                                        planValues.put(DatabaseConstants.KEY_PLANID, newPlanId);
                                        int updated = cr.update(
                                                ContentUris.withAppendedId(Template.CONTENT_URI, templateId),
                                                planValues, null, null);
                                        if (updated > 0) {
                                            Log.i(TAG, "updated plan id in template:" + templateId);
                                            restoredPlansCount++;
                                        }
                                    } else {
                                        restoredPlansCount++;
                                    }
                                    continue;
                                }
                                eventCursor.close();
                            }
                            Log.d(TAG, String.format(
                                    "Looking for event with uuid %s did not find, now reconstructing from cache",
                                    uuid));
                            eventCursor = cr.query(TransactionProvider.EVENT_CACHE_URI, buildEventProjection(),
                                    Events.DESCRIPTION + " LIKE ?", new String[] { "%" + uuid + "%" }, null);
                            boolean found = false;
                            if (eventCursor != null) {
                                if (eventCursor.moveToFirst()) {
                                    found = true;
                                    copyEventData(eventCursor, eventValues);
                                    if (insertEventAndUpdatePlan(eventValues, templateId)) {
                                        Log.i(TAG, "updated plan id in template:" + templateId);
                                        restoredPlansCount++;
                                    }
                                }
                                eventCursor.close();
                            }
                            if (!found) {
                                //need to set eventId to null
                                planValues.putNull(DatabaseConstants.KEY_PLANID);
                                getContentResolver().update(
                                        ContentUris.withAppendedId(Template.CONTENT_URI, templateId),
                                        planValues, null, null);
                            }
                        } while (planCursor.moveToNext());
                    }
                    planCursor.close();
                }
            }
            c.close();
        }
    }
    return new Result(true, R.string.restore_calendar_success, restoredPlansCount);
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String MakeDir(String sDir) {
    String sTmpDir = fixFileName(sDir);
    String sRet = sErrorPrefix + "Could not create the directory " + sTmpDir;
    if (sTmpDir.contains("org.mozilla.fennec") || sTmpDir.contains("org.mozilla.firefox")) {
        ContentResolver cr = contextWrapper.getContentResolver();
        Uri ffxFiles = Uri//from  w  w w.  ja  v  a  2  s.  c o m
                .parse("content://" + (sTmpDir.contains("fennec") ? fenProvider : ffxProvider) + "/dir");
        ContentValues cv = new ContentValues();

        if (cr.update(ffxFiles, cv, sTmpDir, null) == 1) {
            sRet = sDir + " successfully created";
        }
    } else {
        File dir = new File(sTmpDir);

        if (dir.mkdirs()) {
            sRet = sDir + " successfully created";
        }
    }

    return (sRet);
}

From source file:org.getlantern.firetweet.util.Utils.java

public static boolean setLastSeen(Context context, long userId, long time) {
    final ContentResolver cr = context.getContentResolver();
    final ContentValues values = new ContentValues();
    if (time > 0) {
        values.put(CachedUsers.LAST_SEEN, time);
    } else {//w  w  w . j ava 2  s . c  om
        // Zero or negative value means remove last seen
        values.putNull(CachedUsers.LAST_SEEN);
    }
    final Expression where = Expression.equals(CachedUsers.USER_ID, userId);
    return cr.update(CachedUsers.CONTENT_URI, values, where.getSQL(), null) != 0;
}

From source file:com.android.providers.contacts.ContactsSyncAdapter.java

private void getServerPhotos(SyncContext context, String feedUrl, int maxDownloads, GDataSyncData syncData,
        SyncResult syncResult) {/*from w  w  w .  ja  v  a2s  . c  o  m*/
    final ContentResolver cr = getContext().getContentResolver();
    Cursor cursor = cr.query(Photos.CONTENT_URI,
            new String[] { Photos._SYNC_ID, Photos._SYNC_VERSION, Photos.PERSON_ID, Photos.DOWNLOAD_REQUIRED,
                    Photos._ID },
            "" + "_sync_account=? AND download_required != 0", new String[] { getAccount() }, null);
    try {
        int numFetched = 0;
        while (cursor.moveToNext()) {
            if (numFetched >= maxDownloads) {
                break;
            }
            String photoSyncId = cursor.getString(0);
            String photoVersion = cursor.getString(1);
            long person = cursor.getLong(2);
            String photoUrl = feedUrl + "/" + photoSyncId;
            long photoId = cursor.getLong(4);

            try {
                context.setStatusText("Downloading photo " + photoSyncId);
                ++numFetched;
                ++mPhotoDownloads;
                InputStream inputStream = mContactsClient.getMediaEntryAsStream(photoUrl, getAuthToken());
                savePhoto(person, inputStream, photoVersion);
                syncResult.stats.numUpdates++;
            } catch (IOException e) {
                if (Log.isLoggable(TAG, Log.VERBOSE)) {
                    Log.d(TAG, "error downloading " + photoUrl, e);
                }
                syncResult.stats.numIoExceptions++;
                return;
            } catch (HttpException e) {
                switch (e.getStatusCode()) {
                case HttpException.SC_UNAUTHORIZED:
                    if (Config.LOGD) {
                        Log.d(TAG, "not authorized to download " + photoUrl, e);
                    }
                    syncResult.stats.numAuthExceptions++;
                    return;
                case HttpException.SC_FORBIDDEN:
                case HttpException.SC_NOT_FOUND:
                    final String exceptionMessage = e.getMessage();
                    if (Config.LOGD) {
                        Log.d(TAG, "unable to download photo " + photoUrl + ", " + exceptionMessage
                                + ", ignoring");
                    }
                    ContentValues values = new ContentValues();
                    values.put(Photos.SYNC_ERROR, exceptionMessage);
                    Uri photoUri = Uri.withAppendedPath(ContentUris.withAppendedId(People.CONTENT_URI, photoId),
                            Photos.CONTENT_DIRECTORY);
                    cr.update(photoUri, values, null /* where */, null /* where args */);
                    break;
                default:
                    if (Config.LOGD) {
                        Log.d(TAG, "error downloading " + photoUrl, e);
                    }
                    syncResult.stats.numIoExceptions++;
                    return;
                }
            }
        }
        final boolean hasMoreToSync = numFetched < cursor.getCount();
        GDataSyncData.FeedData feedData = new GDataSyncData.FeedData(0 /* no update time */, numFetched,
                hasMoreToSync, null /* no lastId */, 0 /* no feed index */);
        syncData.feedData.put(feedUrl, feedData);
    } finally {
        cursor.close();
    }
}

From source file:gov.wa.wsdot.android.wsdot.service.BorderWaitSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from w w w .  ja  v a2s. co  m
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "border_wait" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaMinutes = (now - lastUpdated) / DateUtils.MINUTE_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaMinutes + " min");
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.MINUTE_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(BORDER_WAIT_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("waittimes");
            JSONArray items = result.getJSONArray("items");
            List<ContentValues> times = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues timesValues = new ContentValues();
                timesValues.put(BorderWait.BORDER_WAIT_ID, item.getInt("id"));
                timesValues.put(BorderWait.BORDER_WAIT_TITLE, item.getString("name"));
                timesValues.put(BorderWait.BORDER_WAIT_UPDATED, item.getString("updated"));
                timesValues.put(BorderWait.BORDER_WAIT_LANE, item.getString("lane"));
                timesValues.put(BorderWait.BORDER_WAIT_ROUTE, item.getInt("route"));
                timesValues.put(BorderWait.BORDER_WAIT_DIRECTION, item.getString("direction"));
                timesValues.put(BorderWait.BORDER_WAIT_TIME, item.getInt("wait"));

                if (starred.contains(item.getInt("id"))) {
                    timesValues.put(BorderWait.BORDER_WAIT_IS_STARRED, 1);
                }

                times.add(timesValues);

            }

            // Purge existing border wait times covered by incoming data
            resolver.delete(BorderWait.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(BorderWait.CONTENT_URI, times.toArray(new ContentValues[times.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "border_wait" });

            responseString = "OK";

        } catch (Exception e) {
            Log.e(DEBUG_TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent.setAction("gov.wa.wsdot.android.wsdot.intent.action.BORDER_WAIT_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

From source file:gov.wa.wsdot.android.wsdot.service.FerriesTerminalSailingSpaceSyncService.java

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/* w w  w.j a  va 2 s . co  m*/
    long now = System.currentTimeMillis();
    boolean shouldUpdate = true;
    String responseString = "";
    DateFormat dateFormat = new SimpleDateFormat("MMMM d, yyyy h:mm a");

    /** 
     * Check the cache table for the last time data was downloaded. If we are within
     * the allowed time period, don't sync, otherwise get fresh data from the server.
     */
    try {
        cursor = resolver.query(Caches.CONTENT_URI, new String[] { Caches.CACHE_LAST_UPDATED },
                Caches.CACHE_TABLE_NAME + " LIKE ?", new String[] { "ferries_terminal_sailing_space" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            shouldUpdate = (Math.abs(now - lastUpdated) > (15 * DateUtils.SECOND_IN_MILLIS));
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Ability to force a refresh of camera data.
    boolean forceUpdate = intent.getBooleanExtra("forceUpdate", false);

    if (shouldUpdate || forceUpdate) {
        List<Integer> starred = new ArrayList<Integer>();

        starred = getStarred();

        try {
            URL url = new URL(TERMINAL_SAILING_SPACE_URL);
            URLConnection urlConn = url.openConnection();

            BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
            String jsonFile = "";
            String line;

            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONArray array = new JSONArray(jsonFile);
            List<ContentValues> terminal = new ArrayList<ContentValues>();

            int numItems = array.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = array.getJSONObject(j);
                ContentValues sailingSpaceValues = new ContentValues();
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ID, item.getInt("TerminalID"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_NAME,
                        item.getString("TerminalName"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_ABBREV,
                        item.getString("TerminalAbbrev"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_DEPARTING_SPACES,
                        item.getString("DepartingSpaces"));
                sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_LAST_UPDATED,
                        dateFormat.format(new Date(System.currentTimeMillis())));

                if (starred.contains(item.getInt("TerminalID"))) {
                    sailingSpaceValues.put(FerriesTerminalSailingSpace.TERMINAL_IS_STARRED, 1);
                }

                terminal.add(sailingSpaceValues);
            }

            // Purge existing terminal sailing space items covered by incoming data
            resolver.delete(FerriesTerminalSailingSpace.CONTENT_URI, null, null);
            // Bulk insert all the new terminal sailing space items
            resolver.bulkInsert(FerriesTerminalSailingSpace.CONTENT_URI,
                    terminal.toArray(new ContentValues[terminal.size()]));
            // Update the cache table with the time we did the update
            ContentValues values = new ContentValues();
            values.put(Caches.CACHE_LAST_UPDATED, System.currentTimeMillis());
            resolver.update(Caches.CONTENT_URI, values, Caches.CACHE_TABLE_NAME + "=?",
                    new String[] { "ferries_terminal_sailing_space" });

            responseString = "OK";

        } catch (Exception e) {
            Log.e(TAG, "Error: " + e.getMessage());
            responseString = e.getMessage();
        }
    } else {
        responseString = "NOP";
    }

    Intent broadcastIntent = new Intent();
    broadcastIntent
            .setAction("gov.wa.wsdot.android.wsdot.intent.action.FERRIES_TERMINAL_SAILING_SPACE_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}