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.nbos.phonebook.sync.platform.ContactManager.java

public static void resetDirtyGroups(Context ctx) {
    ContentResolver cr = ctx.getContentResolver();
    ContentValues values = new ContentValues();
    values.put(ContactsContract.Groups.DIRTY, "0");
    int num = cr.update(ContactsContract.Groups.CONTENT_URI, values, null, null);
    Log.i(tag, "Updated " + num + " groups to dirty = 0");
    num = cr.delete(SyncManager.addCallerIsSyncAdapterParameter(Groups.CONTENT_URI),
            Groups.DELETED + " = 1 " + " and " + Groups.ACCOUNT_TYPE + " = ? ",
            new String[] { Constants.ACCOUNT_TYPE });
    Log.i(tag, "Deleted " + num + " groups");
}

From source file:Main.java

public static String checkNull(Context context, int lastImageId, File fileCapture) {
    final String[] imageColumns = { Images.Media._ID, Images.Media.DATA };
    final String imageOrderBy = Images.Media._ID + " DESC";
    final String imageWhere = Images.Media._ID + ">?";
    final String[] imageArguments = { Integer.toString(lastImageId) };

    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(Images.Media.EXTERNAL_CONTENT_URI, imageColumns, imageWhere,
            imageArguments, imageOrderBy);
    if (cursor == null)
        return null;

    String newpath = null;//from  w  w w  .j av  a  2 s.c  o  m
    if (cursor.getCount() >= 2) {
        for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
            int id = cursor.getInt(cursor.getColumnIndex(Images.Media._ID));
            String data = cursor.getString(cursor.getColumnIndex(Images.Media.DATA));
            if (data.equals(fileCapture.getPath())) {
                int rows = contentResolver.delete(Images.Media.EXTERNAL_CONTENT_URI, Images.Media._ID + "=?",
                        new String[] { Long.toString(id) });
                boolean ok = fileCapture.delete();

            } else {
                newpath = data;
            }
        }
    } else {
        newpath = fileCapture.getPath();
        Log.e("MediaUtils", "Not found duplicate.");
    }

    cursor.close();
    return newpath;
}

From source file:com.ksk.droidbatterybooster.provider.TimeSchedule.java

public static void deleteTimeSchedule(Context context, long scheduleId) {
    if (scheduleId == -1)
        return;/*from  w w w .jav  a  2  s .c  o m*/

    ContentResolver contentResolver = context.getContentResolver();

    Uri uri = ContentUris.withAppendedId(CONTENT_URI, scheduleId);
    contentResolver.delete(uri, "", null);

    setNextAction(context);
}

From source file:com.smarthome.deskclock.Alarms.java

/**
 * Removes an existing Alarm.  If this alarm is snoozing, disables
 * snooze.  Sets next alert.//from  w w  w.j a va 2  s.c o m
 */
public static void deleteAlarm(Context context, int alarmId) {
    if (alarmId == -1)
        return;

    ContentResolver contentResolver = context.getContentResolver();
    /* If alarm is snoozing, lose it */
    disableSnoozeAlert(context, alarmId);

    Uri uri = ContentUris.withAppendedId(Alarm.Columns.CONTENT_URI, alarmId);
    contentResolver.delete(uri, "", null);

    setNextAlert(context);
    //        postAlarmId(context,alarm);
}

From source file:com.stockita.popularmovie.utility.Utilities.java

/**
 * Same as above but this one must get user input to search for a movie.
 *//*from   w w  w  . jav  a2  s.c  o m*/
public static void downloadSearchData(Context context, String searchForAMovie) {

    // Download data and store the string in SharedPreferences
    String dataPopularOne = getMovieData(URL_SEARCH_PAGE_ONE + searchForAMovie, context);
    setMovieId(context, "searchMovieOne", dataPopularOne);

    String dataPopularTwo = getMovieData(URL_SEARCH_PAGE_TWO + searchForAMovie, context);
    setMovieId(context, "searchMovieTwo", dataPopularTwo);

    // Delete search data before insert new data
    try {
        ContentResolver contentResolver = context.getContentResolver();
        contentResolver.delete(ContractMovies.MovieEntry.CONTENT_URI,
                ContractMovies.MovieEntry.COLUMN_SORT_GROUP + "=?", new String[] { "search" });
        contentResolver.delete(ContractMovies.GenreEntry.CONTENT_URI,
                ContractMovies.GenreEntry.COLUMN_SORT_GROUP + "=?", new String[] { "search" });
    } catch (Exception e) {
        Log.e(LOG_TAG, e.toString());
    }

    // Parse and insert new data
    parseFeed(context, getMovieId(context, "searchMovieOne"), "searchOne", "search");
    parseFeed(context, getMovieId(context, "searchMovieTwo"), "searchTwo", "search");

}

From source file:com.stockita.popularmovie.utility.Utilities.java

/**
 * Download and Parse//from   w  w  w .j  a v a2  s  .com
 */
public static void downloadAllData(Context context) {
    // Download data and store the string in SharedPreferences
    String dataNowPlayingOne = getMovieData(URL_THE_MOVIE_DB_NOWPLAYING_PageOne, context);
    setMovieId(context, "dataNowPlayingOne", dataNowPlayingOne);

    String dataNowPlayingTwo = getMovieData(URL_THE_MOVIE_DB_NOWPLAYING_PageTwo, context);
    setMovieId(context, "dataNowPlayingTwo", dataNowPlayingTwo);

    String dataUpcomingOne = getMovieData(URL_THE_MOVIE_DB_UPCOMING_PageOne, context);
    setMovieId(context, "dataUpcomingOne", dataUpcomingOne);

    String dataUpcomingTwo = getMovieData(URL_THE_MOVIE_DB_UPCOMING_PageTwo, context);
    setMovieId(context, "dataUpcomingTwo", dataUpcomingTwo);

    String dataPopularOne = getMovieData(URL_THE_MOVIE_DB_POPULAR_PageOne, context);
    setMovieId(context, "dataPopularOne", dataPopularOne);

    String dataPopularTwo = getMovieData(URL_THE_MOVIE_DB_POPULAR_PageTwo, context);
    setMovieId(context, "dataPopularTwo", dataPopularTwo);

    String dataRatingOne = getMovieData(URL_THE_MOVIE_DB_RATING_PageOne, context);
    setMovieId(context, "dataRatingOne", dataRatingOne);

    String dataRatingTwo = getMovieData(URL_THE_MOVIE_DB_RATING_PageTwo, context);
    setMovieId(context, "dataRatingTwo", dataRatingTwo);

    // Delete all data before insert new data
    if (sNetworkResponse) {
        try {
            ContentResolver contentResolver = context.getContentResolver();
            contentResolver.delete(ContractMovies.MovieEntry.CONTENT_URI, null, null);
            contentResolver.delete(ContractMovies.GenreEntry.CONTENT_URI, null, null);
            contentResolver.delete(ContractMovies.CreditEntry.CONTENT_URI, null, null);
            contentResolver.delete(ContractMovies.TrailerEntry.CONTENT_URI, null, null);
            contentResolver.delete(ContractMovies.PosterEntry.CONTENT_URI, null, null);
            contentResolver.delete(ContractMovies.ReviewEntry.CONTENT_URI, null, null);
        } catch (Exception e) {
            Log.e(LOG_TAG, e.toString());
        }

        // Parse and insert data into database
        parseFeed(context, getMovieId(context, "dataNowPlayingOne"), "nowplayingseven", "nowplaying");
        parseFeed(context, getMovieId(context, "dataNowPlayingTwo"), "nowplayingeight", "nowplaying");
        parseFeed(context, getMovieId(context, "dataUpcomingOne"), "upcomingfive", "upcoming");
        parseFeed(context, getMovieId(context, "dataUpcomingTwo"), "upcomingsix", "upcoming");
        parseFeed(context, getMovieId(context, "dataPopularOne"), "popularone", "popular");
        parseFeed(context, getMovieId(context, "dataPopularTwo"), "populartwo", "popular");
        parseFeed(context, getMovieId(context, "dataRatingOne"), "ratingthree", "rating");
        parseFeed(context, getMovieId(context, "dataRatingTwo"), "ratingfour", "rating");
    }
}

From source file:com.example.android.ennis.barrett.popularmovies.asynchronous.TMDbSyncUtil.java

/**
 * Removes all data from themovies, thevideos, and thereviews tables.  Does not remove data
 * flagged favorite but the columns istoprated, and ispopular will be set to false, "0".
 * @param context//  ww  w . j a  v  a 2 s. c o  m
 */
public static void deletePopularAndTopRated(Context context) {
    ContentResolver contentResolver = context.getContentResolver();

    ContentValues removePopAndTop = new ContentValues(2);
    removePopAndTop.put(TMDbContract.Movies.IS_POPULAR, "0");
    removePopAndTop.put(TMDbContract.Movies.IS_TOP_RATED, "0");

    contentResolver.update(TMDbContract.Movies.URI, removePopAndTop, TMDbContract.Movies.IS_FAVORITE + " = ?",
            new String[] { "1" });

    contentResolver.delete(TMDbContract.Movies.URI,
            TMDbContract.Movies.IS_POPULAR + " = ? OR " + TMDbContract.Movies.IS_TOP_RATED + " = ?",
            new String[] { "1", "1" });

    Cursor favoriteMovieIds = getFavoriteIds(context);

    int numberOfIds = favoriteMovieIds.getCount();
    String[] movieIds = new String[numberOfIds];
    String whereClauseVideos = "";
    String whereClauseReviews = "";

    for (int i = 0; i < numberOfIds; i++) {
        favoriteMovieIds.moveToNext();
        movieIds[i] = Integer.toString(
                favoriteMovieIds.getInt(favoriteMovieIds.getColumnIndex(TMDbContract.Movies.MOVIE_ID)));
        if (i == numberOfIds - 1) {
            whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? ";
            whereClauseReviews += TMDbContract.Videos.MOVIE_IDS + " != ? ";
        } else {
            whereClauseVideos += TMDbContract.Videos.MOVIE_IDS + " != ? OR ";
            whereClauseReviews += TMDbContract.Reviews.MOVIE_IDS + " != ? OR ";
        }
    }

    contentResolver.delete(TMDbContract.Videos.URI, whereClauseVideos, movieIds);
    contentResolver.delete(TMDbContract.Reviews.URI, whereClauseReviews, movieIds);
}

From source file:saschpe.birthdays.service.CalendarSyncService.java

/**
 * Syncing work-horse.//  w w  w.  jav  a2  s  . co m
 *
 * Simply runs in current thread if invoked directly.
 */
public static void performSync(Context context) {
    Log.d(TAG, "Perform sync...");

    ContentResolver cr = context.getContentResolver();
    if (cr == null) {
        Log.e(TAG, "Unable to get content resolver!");
        return;
    }

    long calendarId = getCalendar(context);
    int deletedRows = cr.delete(getCalendarUri(context, CalendarContract.Events.CONTENT_URI),
            CalendarContract.Events.CALENDAR_ID + " = ?", new String[] { String.valueOf(calendarId) });
    Log.i(TAG, "Removed " + deletedRows + " rows from calendar " + calendarId);
    final long[] reminderMinutes = PreferencesHelper.getReminderMinutes(context);
    ArrayList<ContentProviderOperation> operations = new ArrayList<>();

    Cursor cursor = getContactsEvents(context, cr);
    if (cursor == null) {
        Log.e(TAG, "Failed to parse contacts events");
    }

    try {
        final int eventDateColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
        final int displayNameColumn = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        final int eventTypeColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);
        final int eventCustomLabelColumn = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Event.LABEL);
        final int eventLookupKeyColumn = cursor
                .getColumnIndex(ContactsContract.CommonDataKinds.Event.LOOKUP_KEY);

        int backRef = 0;

        // Loop over all events
        while (cursor != null && cursor.moveToNext()) {
            final String eventDateString = cursor.getString(eventDateColumn);
            final String displayName = cursor.getString(displayNameColumn);
            final int eventType = cursor.getInt(eventTypeColumn);
            final String eventLookupKey = cursor.getString(eventLookupKeyColumn);
            final Date eventDate = parseEventDateString(eventDateString);

            if (eventDate != null) {
                // Get year from event
                Calendar eventCalendar = Calendar.getInstance();
                eventCalendar.setTime(eventDate);
                int eventYear = eventCalendar.get(Calendar.YEAR);
                //Log.debug("Event year: " + eventYear);

                // If year < 1800 don't show brackets with age behind name. When no year is defined
                // parseEventDateString() sets it to 1700. Also iCloud for example sets year to
                // 1604 if no year is defined in their user interface.
                boolean hasYear = false;
                if (eventYear >= 1800) {
                    hasYear = true;
                }

                // Get current year
                Calendar currentCalendar = Calendar.getInstance();
                final int currentYear = currentCalendar.get(Calendar.YEAR);

                // Insert events for the past 2 years and the next 5 years. Events are not inserted
                // as recurring events to have different titles with birthday age in it.
                final int startYear = currentYear - 1;
                final int endYear = currentYear + 3;

                for (int year = startYear; year <= endYear; year++) {
                    // Calculate age
                    final int age = year - eventYear;
                    // If birthday has year and age of this event >= 0, display age in title
                    boolean includeAge = false;
                    if (hasYear && age >= 0) {
                        includeAge = true;
                    }
                    //Log.debug("Year: " + year + " age: " + age + " include age: " + includeAge);

                    String title = null;
                    String description = "";
                    if (displayName != null) {
                        switch (eventType) {
                        case ContactsContract.CommonDataKinds.Event.TYPE_CUSTOM:
                            String eventCustomLabel = cursor.getString(eventCustomLabelColumn);
                            if (eventCustomLabel != null) {
                                title = context.getString(R.string.event_custom_title_template, displayName,
                                        eventCustomLabel);
                            } else {
                                title = context.getString(R.string.event_other_title_template, displayName);
                            }
                            break;
                        case ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY:
                            title = context.getString(R.string.event_anniversary_title_template, displayName);
                            if (age == 1) {
                                description = context.getString(
                                        R.string.event_anniversary_description_singular_template, displayName,
                                        age);
                            } else {
                                description = context.getString(
                                        R.string.event_anniversary_description_plural_template, displayName,
                                        age);
                            }
                            break;
                        case ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY:
                            title = context.getString(R.string.event_birthday_title_template, displayName);
                            if (age == 1) {
                                description = context.getString(
                                        R.string.event_birthday_description_singular_template, displayName,
                                        eventYear, age);
                            } else {
                                description = context.getString(
                                        R.string.event_birthday_description_plural_template, displayName,
                                        eventYear, age);
                            }
                            break;
                        default:
                            // Includes ContactsContract.CommonDataKinds.Event.TYPE_OTHER
                            title = String.format(context.getString(R.string.event_other_title_template),
                                    displayName);
                            break;
                        }
                    }

                    if (title != null) {
                        Log.d(TAG, "Title: " + title + " backref: " + backRef);
                        operations.add(insertEvent(context, calendarId, eventDate, year, title, description,
                                eventLookupKey));

                        // Gets ContentProviderOperation to insert new reminder to the ContentProviderOperation
                        // with the given backRef. This is done using "withValueBackReference"
                        int reminderOperations = 0;
                        for (long reminderMinute : reminderMinutes) {
                            if (reminderMinute >= -1) {
                                ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(
                                        getCalendarUri(context, CalendarContract.Reminders.CONTENT_URI));
                                // Add reminder to last added event identified by backRef
                                // see http://stackoverflow.com/questions/4655291/semantics-of-withvaluebackreference
                                builder.withValueBackReference(CalendarContract.Reminders.EVENT_ID, backRef);
                                builder.withValue(CalendarContract.Reminders.MINUTES, reminderMinute);
                                builder.withValue(CalendarContract.Reminders.METHOD,
                                        CalendarContract.Reminders.METHOD_ALERT);
                                operations.add(builder.build());
                                reminderOperations += 1;
                            }
                        }
                        // Back reference for the next reminders, 1 is for the event
                        backRef += 1 + reminderOperations;
                    } else {
                        Log.d(TAG, "Event title empty, won't insert event and reminder");
                    }

                    // Intermediate commit, otherwise the binder transaction fails on large operation list
                    if (operations.size() > 200) {
                        applyBatchOperation(cr, operations);
                        backRef = 0;
                        operations.clear();
                    }
                }
            }
        }
    } finally {
        if (cursor != null && !cursor.isClosed())
            cursor.close();
    }

    // Create remaining events (that haven't been created by intermediate commits):
    if (operations.size() > 0) {
        applyBatchOperation(cr, operations);
    }

    LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(ACTION_SYNC_DONE));
    Log.d(TAG, "Done performing sync...");
}

From source file:com.manning.androidhacks.hack043.service.NoBatchService.java

@Override
protected void onHandleIntent(Intent intent) {

    ContentResolver contentResolver = getContentResolver();
    contentResolver.delete(NoBatchNumbersContentProvider.CONTENT_URI, null, null);

    for (int i = 1; i <= 100; i++) {
        ContentValues cv = new ContentValues();
        cv.put(NoBatchNumbersContentProvider.COLUMN_TEXT, "" + i);
        contentResolver.insert(NoBatchNumbersContentProvider.CONTENT_URI, cv);
    }/* w w w  . java  2 s  .  c om*/
}

From source file:it.imwatch.nfclottery.dialogs.ClearDBAlertDialog.java

/**
 * Clears the database.//  w  ww. j av  a 2 s.  co m
 */
private void clearDB() {
    final Activity activity = getActivity();
    if (activity == null) {
        Log.e(TAG, "Not attached to Activity: cannot clear DB");
        return;
    }

    ContentResolver cr = activity.getContentResolver();
    cr.delete(NFCMLContent.Geeks.CONTENT_URI, null, null);

    if (activity instanceof MainActivity) {
        final MainActivity mainActivity = (MainActivity) activity;
        mainActivity.showCroutonNao(mainActivity.getString(R.string.info_db_cleared), Style.INFO);
        mainActivity.updateParticipantsCount();
    } else {
        Log.e(TAG, "The parent Activity is not MainActivity! Wat is this I don't even");
        if (DEBUG)
            Log.d(TAG, "Activity class: " + activity.getLocalClassName());
        Toast.makeText(activity, activity.getString(R.string.clear_db_failed_wrong_parent), Toast.LENGTH_SHORT)
                .show();
    }
}