Example usage for android.content ContentResolver delete

List of usage examples for android.content ContentResolver delete

Introduction

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

Prototype

public final int delete(@RequiresPermission.Write @NonNull Uri url, @Nullable String where,
        @Nullable String[] selectionArgs) 

Source Link

Document

Deletes row(s) specified by a content URI.

Usage

From source file:de.vanita5.twittnuker.util.Utils.java

public static ParcelableStatus findStatus(final Context context, final long account_id, final long status_id)
        throws TwitterException {
    if (context == null || account_id <= 0 || status_id <= 0)
        return null;
    final ParcelableStatus p_status = findStatusInDatabases(context, account_id, status_id);
    if (p_status != null)
        return p_status;
    final Twitter twitter = getTwitterInstance(context, account_id, true);
    if (twitter == null)
        return null;
    final Status status = twitter.showStatus(status_id);
    if (status == null || status.getId() <= 0)
        return null;
    final String where = Statuses.ACCOUNT_ID + " = " + account_id + " AND " + Statuses.STATUS_ID + " = "
            + status.getId();// w  ww. ja  v a2 s .  co m
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(CachedStatuses.CONTENT_URI, where, null);
    resolver.insert(CachedStatuses.CONTENT_URI,
            ContentValuesCreator.makeStatusContentValues(status, account_id));
    return new ParcelableStatus(status, account_id, false);
}

From source file:com.dwdesign.tweetings.util.Utils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;/*  w w w  .ja v a  2  s.  c  o  m*/
    final ContentResolver resolver = context.getContentResolver();
    final int item_limit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(PREFERENCE_KEY_DATABASE_ITEM_LIMIT, PREFERENCE_DEFAULT_DATABASE_ITEM_LIMIT);

    for (final long account_id : getAccountIds(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            final String table = getTableNameForContentUri(uri);
            final StringBuilder where = new StringBuilder();
            where.append(Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(Statuses._ID + " NOT IN (");
            where.append(" SELECT " + Statuses._ID + " FROM " + table);
            where.append(" WHERE " + Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + Statuses.STATUS_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameForContentUri(uri);
            final StringBuilder where = new StringBuilder();
            where.append(DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(DirectMessages._ID + " NOT IN (");
            where.append(" SELECT " + DirectMessages._ID + " FROM " + table);
            where.append(" WHERE " + DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + DirectMessages.MESSAGE_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
    }
    // Clean cached users.
    {
        final Uri uri = CachedUsers.CONTENT_URI;
        final String table = getTableNameForContentUri(uri);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses._ID + " NOT IN (");
        where.append(" SELECT " + CachedUsers._ID + " FROM " + table);
        where.append(" LIMIT " + (int) (Math.sqrt(item_limit) * 100) + ")");
        resolver.delete(uri, where.toString(), null);
    }
}

From source file:org.mariotaku.twidere.util.Utils.java

public static synchronized void cleanDatabasesByItemLimit(final Context context) {
    if (context == null)
        return;//from  ww  w.j  ava2  s. c  o m
    final ContentResolver resolver = context.getContentResolver();
    final int item_limit = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
            .getInt(PREFERENCE_KEY_DATABASE_ITEM_LIMIT, PREFERENCE_DEFAULT_DATABASE_ITEM_LIMIT);

    for (final long account_id : getAccountIds(context)) {
        // Clean statuses.
        for (final Uri uri : STATUSES_URIS) {
            if (CachedStatuses.CONTENT_URI.equals(uri)) {
                continue;
            }
            final String table = getTableNameByUri(uri);
            final StringBuilder where = new StringBuilder();
            where.append(Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(Statuses._ID + " NOT IN (");
            where.append(" SELECT " + Statuses._ID + " FROM " + table);
            where.append(" WHERE " + Statuses.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + Statuses.STATUS_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
        for (final Uri uri : DIRECT_MESSAGES_URIS) {
            final String table = getTableNameByUri(uri);
            final StringBuilder where = new StringBuilder();
            where.append(DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" AND ");
            where.append(DirectMessages._ID + " NOT IN (");
            where.append(" SELECT " + DirectMessages._ID + " FROM " + table);
            where.append(" WHERE " + DirectMessages.ACCOUNT_ID + " = " + account_id);
            where.append(" ORDER BY " + DirectMessages.MESSAGE_ID + " DESC");
            where.append(" LIMIT " + item_limit + ")");
            resolver.delete(uri, where.toString(), null);
        }
    }
    // Clean cached values.
    for (final Uri uri : CACHE_URIS) {
        final String table = getTableNameByUri(uri);
        final StringBuilder where = new StringBuilder();
        where.append(Statuses._ID + " NOT IN (");
        where.append(" SELECT " + BaseColumns._ID + " FROM " + table);
        where.append(" LIMIT " + (int) (Math.sqrt(item_limit) * 100) + ")");
        resolver.delete(uri, where.toString(), null);
    }
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from ww w.ja v  a2  s .  c  o 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);
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/* ww w.  ja va 2 s  . 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:org.getlantern.firetweet.util.Utils.java

@NonNull
public static ParcelableStatus findStatus(final Context context, final long accountId, final long statusId)
        throws TwitterException {
    if (context == null)
        throw new NullPointerException();
    final ParcelableStatus cached = findStatusInDatabases(context, accountId, statusId);
    if (cached != null)
        return cached;
    final Twitter twitter = getTwitterInstance(context, accountId, true);
    if (twitter == null)
        throw new TwitterException("Account does not exist");
    final Status status = twitter.showStatus(statusId);
    final String where = Expression.and(Expression.equals(Statuses.ACCOUNT_ID, accountId),
            Expression.equals(Statuses.STATUS_ID, statusId)).getSQL();
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(CachedStatuses.CONTENT_URI, where, null);
    resolver.insert(CachedStatuses.CONTENT_URI, ContentValuesCreator.createStatus(status, accountId));
    return new ParcelableStatus(status, accountId, false);
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from w w w. j  a va 2  s  .  c om*/
    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, projection, Caches.CACHE_TABLE_NAME + " LIKE ?",
                new String[] { "cameras" }, null);

        if (cursor != null && cursor.moveToFirst()) {
            long lastUpdated = cursor.getLong(0);
            //long deltaDays = (now - lastUpdated) / DateUtils.DAY_IN_MILLIS;
            //Log.d(DEBUG_TAG, "Delta since last update is " + deltaDays + " day(s)");
            shouldUpdate = (Math.abs(now - lastUpdated) > (7 * DateUtils.DAY_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(CAMERAS_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

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

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

            int numItems = items.length();
            for (int j = 0; j < numItems; j++) {
                JSONObject item = items.getJSONObject(j);
                ContentValues cameraData = new ContentValues();

                cameraData.put(Cameras.CAMERA_ID, item.getString("id"));
                cameraData.put(Cameras.CAMERA_TITLE, item.getString("title"));
                cameraData.put(Cameras.CAMERA_URL, item.getString("url"));
                cameraData.put(Cameras.CAMERA_LATITUDE, item.getString("lat"));
                cameraData.put(Cameras.CAMERA_LONGITUDE, item.getString("lon"));
                cameraData.put(Cameras.CAMERA_HAS_VIDEO, item.getString("video"));
                cameraData.put(Cameras.CAMERA_ROAD_NAME, item.getString("roadName"));

                if (starred.contains(Integer.parseInt(item.getString("id")))) {
                    cameraData.put(Cameras.CAMERA_IS_STARRED, 1);
                }

                cams.add(cameraData);
            }

            // Purge existing cameras covered by incoming data
            resolver.delete(Cameras.CONTENT_URI, null, null);
            // Bulk insert all the new cameras
            resolver.bulkInsert(Cameras.CONTENT_URI, cams.toArray(new ContentValues[cams.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 + " LIKE ?",
                    new String[] { "cameras" });

            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.CAMERAS_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}

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

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
    if (!key.equals(PrefKey.AUTO_BACKUP_DIRTY.getKey())) {
        markDataDirty();/*  w ww.j  a va 2  s.co  m*/
    }
    // TODO: move to TaskExecutionFragment
    if (!key.equals(PrefKey.PLANNER_CALENDAR_ID.getKey())) {
        return;
    }
    String oldValue = mPlannerCalendarId;
    boolean safeToMovePlans = true;
    String newValue = sharedPreferences.getString(PrefKey.PLANNER_CALENDAR_ID.getKey(), "-1");
    if (oldValue.equals(newValue)) {
        return;
    }
    mPlannerCalendarId = newValue;
    if (!newValue.equals("-1")) {
        // if we cannot verify that the oldValue has the correct path
        // we will not risk mangling with an unrelated calendar
        if (!oldValue.equals("-1") && !checkPlannerInternal(oldValue))
            safeToMovePlans = false;
        ContentResolver cr = getContentResolver();
        // we also store the name and account of the calendar,
        // to protect against cases where a user wipes the data of the calendar
        // provider
        // and then accidentally we link to the wrong calendar
        Uri uri = ContentUris.withAppendedId(Calendars.CONTENT_URI, Long.parseLong(mPlannerCalendarId));
        Cursor c = cr.query(uri, new String[] { CALENDAR_FULL_PATH_PROJECTION + " AS path" }, null, null, null);
        if (c != null && c.moveToFirst()) {
            String path = c.getString(0);
            Log.i(TAG, "storing calendar path : " + path);
            PrefKey.PLANNER_CALENDAR_PATH.putString(path);
        } else {
            AcraHelper.report(new IllegalStateException("could not retrieve configured calendar"));
            mPlannerCalendarId = "-1";
            PrefKey.PLANNER_CALENDAR_PATH.remove();
            PrefKey.PLANNER_CALENDAR_ID.putString("-1");
        }
        if (c != null) {
            c.close();
        }
        if (mPlannerCalendarId.equals("-1")) {
            return;
        }
        if (oldValue.equals("-1")) {
            initPlanner();
        } else if (safeToMovePlans) {
            ContentValues eventValues = new ContentValues();
            eventValues.put(Events.CALENDAR_ID, Long.parseLong(newValue));
            Cursor planCursor = cr.query(Template.CONTENT_URI,
                    new String[] { DatabaseConstants.KEY_ROWID, DatabaseConstants.KEY_PLANID },
                    DatabaseConstants.KEY_PLANID + " IS NOT null", null, null);
            if (planCursor != null) {
                if (planCursor.moveToFirst()) {
                    do {
                        long templateId = planCursor.getLong(0);
                        long planId = planCursor.getLong(1);
                        Uri eventUri = ContentUris.withAppendedId(Events.CONTENT_URI, planId);

                        Cursor eventCursor = cr.query(eventUri, buildEventProjection(),
                                Events.CALENDAR_ID + " = ?", new String[] { oldValue }, null);
                        if (eventCursor != null) {
                            if (eventCursor.moveToFirst()) {
                                // Log.i("DEBUG",
                                // DatabaseUtils.dumpCursorToString(eventCursor));
                                copyEventData(eventCursor, eventValues);
                                if (insertEventAndUpdatePlan(eventValues, templateId)) {
                                    Log.i(TAG, "updated plan id in template:" + templateId);
                                    int deleted = cr.delete(eventUri, null, null);
                                    Log.i(TAG, "deleted old event: " + deleted);
                                }
                            }
                            eventCursor.close();
                        }
                    } while (planCursor.moveToNext());
                }
                planCursor.close();
            }
        }
    } else {
        PrefKey.PLANNER_CALENDAR_PATH.remove();
    }
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*from w  w w  .j ava  2s  . 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_schedules" }, 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) > (30 * 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(FERRIES_SCHEDULES_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;

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

            JSONArray items = new JSONArray(jsonFile);
            List<ContentValues> schedules = new ArrayList<ContentValues>();

            int numItems = items.length();
            for (int i = 0; i < numItems; i++) {
                JSONObject item = items.getJSONObject(i);
                ContentValues schedule = new ContentValues();
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ID, item.getInt("RouteID"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_TITLE, item.getString("Description"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_DATE, item.getString("Date"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_ALERT, item.getString("RouteAlert"));
                schedule.put(FerriesSchedules.FERRIES_SCHEDULE_UPDATED, dateFormat
                        .format(new Date(Long.parseLong(item.getString("CacheDate").substring(6, 19)))));

                if (starred.contains(item.getInt("RouteID"))) {
                    schedule.put(FerriesSchedules.FERRIES_SCHEDULE_IS_STARRED, 1);
                }

                schedules.add(schedule);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(FerriesSchedules.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(FerriesSchedules.CONTENT_URI,
                    schedules.toArray(new ContentValues[schedules.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_schedules" });

            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.FERRIES_SCHEDULES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);

}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;//from   w  ww .j  av a2  s . c  o  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[] { "travel_times" }, 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) > (5 * 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(TRAVEL_TIMES_URL);
            URLConnection urlConn = url.openConnection();

            BufferedInputStream bis = new BufferedInputStream(urlConn.getInputStream());
            GZIPInputStream gzin = new GZIPInputStream(bis);
            InputStreamReader is = new InputStreamReader(gzin);
            BufferedReader in = new BufferedReader(is);

            String jsonFile = "";
            String line;

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

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("traveltimes");
            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(TravelTimes.TRAVEL_TIMES_TITLE, item.getString("title"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_CURRENT, item.getInt("current"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_AVERAGE, item.getInt("average"));
                timesValues.put(TravelTimes.TRAVEL_TIMES_DISTANCE, item.getString("distance") + " miles");
                timesValues.put(TravelTimes.TRAVEL_TIMES_ID, Integer.parseInt(item.getString("routeid")));
                timesValues.put(TravelTimes.TRAVEL_TIMES_UPDATED, item.getString("updated"));

                if (starred.contains(Integer.parseInt(item.getString("routeid")))) {
                    timesValues.put(TravelTimes.TRAVEL_TIMES_IS_STARRED, 1);
                }

                times.add(timesValues);
            }

            // Purge existing travel times covered by incoming data
            resolver.delete(TravelTimes.CONTENT_URI, null, null);
            // Bulk insert all the new travel times
            resolver.bulkInsert(TravelTimes.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[] { "travel_times" });

            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.TRAVEL_TIMES_RESPONSE");
    broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
    broadcastIntent.putExtra("responseString", responseString);
    sendBroadcast(broadcastIntent);
}