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:com.google.samples.apps.iosched.service.SessionCalendarService.java

/**
 * Adds or removes a single session to/from the specified Google Calendar.
 *//*from  w ww. j  av a  2 s .  c  o m*/
private ArrayList<ContentProviderOperation> processSessionCalendar(final ContentResolver resolver,
        final long calendarId, final boolean isAddEvent, final Uri sessionUri, final long sessionBlockStart,
        final long sessionBlockEnd, final String sessionTitle, final String sessionRoom) {
    ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();

    // Unable to find the Calendar associated with the user or permissions were revoked.
    if (calendarId == INVALID_CALENDAR_ID || !permissionsAlreadyGranted()) {
        return batch;
    }

    final String calendarEventTitle = makeCalendarEventTitle(sessionTitle);

    Cursor cursor;
    ContentValues values = new ContentValues();

    // Add Calendar event.
    if (isAddEvent) {
        if (sessionBlockStart == 0L || sessionBlockEnd == 0L || sessionTitle == null) {
            LOGW(TAG, "Unable to add a Calendar event due to insufficient input parameters.");
            return batch;
        }

        // Check if the calendar event exists first.  If it does, we don't want to add a
        // duplicate one.
        //noinspection MissingPermission
        cursor = resolver.query(CalendarContract.Events.CONTENT_URI, // URI
                new String[] { CalendarContract.Events._ID }, // Projection
                CalendarContract.Events.CALENDAR_ID + "=? and " // Selection
                        + CalendarContract.Events.TITLE + "=? and " + CalendarContract.Events.DTSTART
                        + ">=? and " + CalendarContract.Events.DTEND + "<=?",
                new String[] { // Selection args
                        Long.valueOf(calendarId).toString(), calendarEventTitle,
                        Long.toString(Config.CONFERENCE_START_MILLIS),
                        Long.toString(Config.CONFERENCE_END_MILLIS) },
                null);

        long newEventId = -1;

        if (cursor != null && cursor.moveToFirst()) {
            // Calendar event already exists for this session.
            newEventId = cursor.getLong(0);
            cursor.close();

            // Data fix (workaround):
            batch.add(ContentProviderOperation.newUpdate(CalendarContract.Events.CONTENT_URI)
                    .withValue(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID())
                    .withSelection(CalendarContract.Events._ID + "=?",
                            new String[] { Long.valueOf(newEventId).toString() })
                    .build());
            // End data fix.

        } else {
            // Calendar event doesn't exist, create it.

            // NOTE: we can't use batch processing here because we need the result of
            // the insert.
            values.clear();
            values.put(CalendarContract.Events.DTSTART, sessionBlockStart);
            values.put(CalendarContract.Events.DTEND, sessionBlockEnd);
            values.put(CalendarContract.Events.EVENT_LOCATION, sessionRoom);
            values.put(CalendarContract.Events.TITLE, calendarEventTitle);
            values.put(CalendarContract.Events.CALENDAR_ID, calendarId);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, Config.CONFERENCE_TIMEZONE.getID());
            @SuppressWarnings("MissingPermission")
            Uri eventUri = resolver.insert(CalendarContract.Events.CONTENT_URI, values);
            String eventId = eventUri.getLastPathSegment();
            if (eventId == null) {
                return batch; // Should be empty at this point
            }

            newEventId = Long.valueOf(eventId);
            // Since we're adding session reminder to system notification, we're not creating
            // Calendar event reminders.  If we were to create Calendar event reminders, this
            // is how we would do it.
            //values.put(CalendarContract.Reminders.EVENT_ID, Integer.valueOf(eventId));
            //values.put(CalendarContract.Reminders.MINUTES, 10);
            //values.put(CalendarContract.Reminders.METHOD,
            //        CalendarContract.Reminders.METHOD_ALERT); // Or default?
            //cr.insert(CalendarContract.Reminders.CONTENT_URI, values);
            //values.clear();
        }

        // Update the session in our own provider with the newly created calendar event ID.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, newEventId);
        resolver.update(sessionUri, values, null, null);

    } else {
        // Remove Calendar event, if exists.

        // Get the event calendar id.
        cursor = resolver.query(sessionUri, new String[] { ScheduleContract.Sessions.SESSION_CAL_EVENT_ID },
                null, null, null);
        long calendarEventId = -1;
        if (cursor != null && cursor.moveToFirst()) {
            calendarEventId = cursor.getLong(0);
            cursor.close();
        }

        // Try to remove the Calendar Event based on key.  If successful, move on;
        // otherwise, remove the event based on Event title.
        int affectedRows = 0;
        if (calendarEventId != -1) {
            //noinspection MissingPermission
            affectedRows = resolver.delete(CalendarContract.Events.CONTENT_URI,
                    CalendarContract.Events._ID + "=?",
                    new String[] { Long.valueOf(calendarEventId).toString() });
        }

        if (affectedRows == 0) {
            //noinspection MissingPermission
            resolver.delete(CalendarContract.Events.CONTENT_URI,
                    String.format("%s=? and %s=? and %s=? and %s=?", CalendarContract.Events.CALENDAR_ID,
                            CalendarContract.Events.TITLE, CalendarContract.Events.DTSTART,
                            CalendarContract.Events.DTEND),
                    new String[] { Long.valueOf(calendarId).toString(), calendarEventTitle,
                            Long.valueOf(sessionBlockStart).toString(),
                            Long.valueOf(sessionBlockEnd).toString() });
        }

        // Remove the session and calendar event association.
        values.clear();
        values.put(ScheduleContract.Sessions.SESSION_CAL_EVENT_ID, (Long) null);
        resolver.update(sessionUri, values, null, null);
    }

    return batch;
}

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

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

    String url = String.format(URL_GAME_LIST, mLocale);
    String page = getResponse(url);

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

    long accountId = account.getId();
    String[] queryParams = new String[1];
    int rowNo = 0;
    boolean changed = false;
    Cursor c;//from   w ww  . j av a 2 s.  c  om
    ContentValues cv;
    long updated = System.currentTimeMillis();
    List<ContentValues> newCvs = new ArrayList<ContentValues>(100);
    ContentResolver cr = mContext.getContentResolver();
    List<String> gameIds = new ArrayList<String>(50);

    Matcher m = PATTERN_GAME_ITEM.matcher(page);
    while (m.find()) {
        String content = m.group(1);
        App.logv(" *** found it: " + content);
        Matcher im = PATTERN_GAME_TITLE_ID.matcher(content);
        if (!im.find())
            continue;

        String uid = im.group(1);
        String title = htmlDecode(im.group(2));
        String boxArtUrl = null;
        int gpAcquired = 0;
        int achUnlocked = 0;

        gameIds.add(uid);

        im = PATTERN_GAME_BOX_ART.matcher(content);
        if (im.find())
            boxArtUrl = im.group(1);

        im = PATTERN_GAME_SCORE.matcher(content);
        if (im.find()) {
            try {
                gpAcquired = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        im = PATTERN_GAME_ACHIEVEMENTS.matcher(content);
        if (im.find()) {
            try {
                achUnlocked = Integer.parseInt(im.group(1));
            } catch (NumberFormatException e) {
            }
        }

        // Check to see if we already have a record of this game
        queryParams[0] = uid;
        c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION,
                Games.ACCOUNT_ID + "=" + accountId + " AND " + Games.UID + "=?", queryParams, null);

        try {
            if (c == null || !c.moveToFirst()) // New game
            {
                cv = new ContentValues(15);
                cv.put(Games.ACCOUNT_ID, accountId);
                cv.put(Games.TITLE, title);
                cv.put(Games.UID, uid);
                cv.put(Games.BOXART_URL, boxArtUrl);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.LAST_UPDATED, updated);
                cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                cv.put(Games.POINTS_TOTAL, gpAcquired);
                cv.put(Games.GAME_URL, (String) null);
                cv.put(Games.INDEX, rowNo);

                // Games with no achievements do not need achievement refresh
                cv.put(Games.ACHIEVEMENTS_STATUS, 1);

                newCvs.add(cv);
            } else // Existing game
            {
                long gameId = c.getLong(COLUMN_GAME_ID);
                long lastPlayedTicksRec = c.getLong(COLUMN_GAME_LAST_PLAYED_DATE);

                cv = new ContentValues(15);

                boolean refreshAchievements = true;

                if (refreshAchievements) {
                    cv.put(Games.ACHIEVEMENTS_UNLOCKED, achUnlocked);
                    cv.put(Games.ACHIEVEMENTS_TOTAL, achUnlocked);
                    cv.put(Games.POINTS_ACQUIRED, gpAcquired);
                    cv.put(Games.POINTS_TOTAL, gpAcquired);
                    cv.put(Games.ACHIEVEMENTS_STATUS, 1);
                }

                cv.put(Games.BEACON_SET, 0);
                cv.put(Games.BEACON_TEXT, (String) null);
                cv.put(Games.LAST_PLAYED, 0);
                cv.put(Games.INDEX, rowNo);
                cv.put(Games.LAST_UPDATED, updated);
                cr.update(Games.CONTENT_URI, cv, Games._ID + "=" + gameId, null);

                changed = true;
            }
        } finally {
            if (c != null)
                c.close();
        }

        rowNo++;
    }

    // Remove games that are no longer present
    c = cr.query(Games.CONTENT_URI, GAMES_PROJECTION, Games.ACCOUNT_ID + "=" + accountId, null, null);

    if (c != null) {
        while (c.moveToNext()) {
            if (!gameIds.contains(c.getString(COLUMN_GAME_UID))) {
                // Game is no longer in list of played games; remove it
                cr.delete(ContentUris.withAppendedId(Games.CONTENT_URI, c.getLong(COLUMN_GAME_ID)), null, null);
                changed = true;
            }
        }

        c.close();
    }

    if (App.getConfig().logToConsole())
        started = displayTimeTaken("Game page processing", started);

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

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

        cr.bulkInsert(Games.CONTENT_URI, cvs);

        if (App.getConfig().logToConsole())
            displayTimeTaken("Game page insertion", started);
    }

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

    if (changed)
        cr.notifyChange(Games.CONTENT_URI, null);
}

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

@Override
protected void onHandleIntent(Intent intent) {
    ContentResolver resolver = getContentResolver();
    Cursor cursor = null;/*w  ww  . j a v  a  2 s .com*/
    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[] { "mountain_passes" }, 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();
        buildWeatherPhrases();

        try {
            URL url = new URL(MOUNTAIN_PASS_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 mDateUpdated = "";
            String jsonFile = "";
            String line;
            while ((line = in.readLine()) != null)
                jsonFile += line;
            in.close();

            JSONObject obj = new JSONObject(jsonFile);
            JSONObject result = obj.getJSONObject("GetMountainPassConditionsResult");
            JSONArray passConditions = result.getJSONArray("PassCondition");
            String weatherCondition;
            Integer weather_image;
            Integer forecast_weather_image;
            List<ContentValues> passes = new ArrayList<ContentValues>();

            int numConditions = passConditions.length();
            for (int j = 0; j < numConditions; j++) {
                JSONObject pass = passConditions.getJSONObject(j);
                ContentValues passData = new ContentValues();
                weatherCondition = pass.getString("WeatherCondition");
                weather_image = getWeatherImage(weatherPhrases, weatherCondition);

                String tempDate = pass.getString("DateUpdated");

                try {
                    tempDate = tempDate.replace("[", "");
                    tempDate = tempDate.replace("]", "");

                    String[] a = tempDate.split(",");
                    StringBuilder sb = new StringBuilder();
                    for (int m = 0; m < 5; m++) {
                        sb.append(a[m]);
                        sb.append(",");
                    }
                    tempDate = sb.toString().trim();
                    tempDate = tempDate.substring(0, tempDate.length() - 1);
                    Date date = parseDateFormat.parse(tempDate);
                    mDateUpdated = displayDateFormat.format(date);
                } catch (Exception e) {
                    Log.e(DEBUG_TAG, "Error parsing date: " + tempDate, e);
                    mDateUpdated = "N/A";
                }

                JSONArray forecasts = pass.getJSONArray("Forecast");
                JSONArray forecastItems = new JSONArray();

                int numForecasts = forecasts.length();
                for (int l = 0; l < numForecasts; l++) {
                    JSONObject forecast = forecasts.getJSONObject(l);

                    if (isNight(forecast.getString("Day"))) {
                        forecast_weather_image = getWeatherImage(weatherPhrasesNight,
                                forecast.getString("ForecastText"));
                    } else {
                        forecast_weather_image = getWeatherImage(weatherPhrases,
                                forecast.getString("ForecastText"));
                    }

                    forecast.put("weather_icon", forecast_weather_image);

                    if (l == 0) {
                        if (weatherCondition.equals("")) {
                            weatherCondition = forecast.getString("ForecastText").split("\\.")[0] + ".";
                            weather_image = forecast_weather_image;
                        }
                    }

                    forecastItems.put(forecast);
                }

                passData.put(MountainPasses.MOUNTAIN_PASS_ID, pass.getString("MountainPassId"));
                passData.put(MountainPasses.MOUNTAIN_PASS_NAME, pass.getString("MountainPassName"));
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_ICON, weather_image);
                passData.put(MountainPasses.MOUNTAIN_PASS_FORECAST, forecastItems.toString());
                passData.put(MountainPasses.MOUNTAIN_PASS_WEATHER_CONDITION, weatherCondition);
                passData.put(MountainPasses.MOUNTAIN_PASS_DATE_UPDATED, mDateUpdated);
                passData.put(MountainPasses.MOUNTAIN_PASS_CAMERA, pass.getString("Cameras"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ELEVATION, pass.getString("ElevationInFeet"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TRAVEL_ADVISORY_ACTIVE,
                        pass.getString("TravelAdvisoryActive"));
                passData.put(MountainPasses.MOUNTAIN_PASS_ROAD_CONDITION, pass.getString("RoadCondition"));
                passData.put(MountainPasses.MOUNTAIN_PASS_TEMPERATURE,
                        pass.getString("TemperatureInFahrenheit"));
                JSONObject restrictionOne = pass.getJSONObject("RestrictionOne");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE,
                        restrictionOne.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_ONE_DIRECTION,
                        restrictionOne.getString("TravelDirection"));
                JSONObject restrictionTwo = pass.getJSONObject("RestrictionTwo");
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO,
                        restrictionTwo.getString("RestrictionText"));
                passData.put(MountainPasses.MOUNTAIN_PASS_RESTRICTION_TWO_DIRECTION,
                        restrictionTwo.getString("TravelDirection"));

                if (starred.contains(Integer.parseInt(pass.getString("MountainPassId")))) {
                    passData.put(MountainPasses.MOUNTAIN_PASS_IS_STARRED, 1);
                }

                passes.add(passData);

            }

            // Purge existing mountain passes covered by incoming data
            resolver.delete(MountainPasses.CONTENT_URI, null, null);
            // Bulk insert all the new mountain passes
            resolver.bulkInsert(MountainPasses.CONTENT_URI, passes.toArray(new ContentValues[passes.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[] { "mountain_passes" });

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

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

@SuppressLint("DefaultLocale")
@Override/* w  ww.j  av a 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:com.codename1.impl.android.AndroidImplementation.java

private void clearMediaDB(String lastId, String capturePath) {
    final String[] imageColumns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media.DATE_TAKEN,
            MediaStore.Images.Media.SIZE, MediaStore.Images.Media._ID };
    final String imageOrderBy = MediaStore.Images.Media._ID + " DESC";
    final String imageWhere = MediaStore.Images.Media._ID + ">?";
    final String[] imageArguments = { lastId };
    Cursor imageCursor = getContext().getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            imageColumns, imageWhere, imageArguments, imageOrderBy);
    if (imageCursor.getCount() > 1) {
        while (imageCursor.moveToNext()) {
            int id = imageCursor.getInt(imageCursor.getColumnIndex(MediaStore.Images.Media._ID));
            String path = imageCursor.getString(imageCursor.getColumnIndex(MediaStore.Images.Media.DATA));
            Long takenTimeStamp = imageCursor
                    .getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.DATE_TAKEN));
            Long size = imageCursor.getLong(imageCursor.getColumnIndex(MediaStore.Images.Media.SIZE));
            if (path.contentEquals(capturePath)) {
                // Remove it
                ContentResolver cr = getContext().getContentResolver();
                cr.delete(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, MediaStore.Images.Media._ID + "=?",
                        new String[] { Long.toString(id) });
                break;
            }/*from www  . j av  a 2s. co m*/
        }
    }
    imageCursor.close();
}