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.example.android.sunshine.sync.SunshineSyncTask.java

/**
 * Performs the network request for updated weather, parses the JSON from that request, and
 * inserts the new weather information into our ContentProvider. Will notify the user that new
 * weather has been loaded if the user hasn't been notified of the weather within the last day
 * AND they haven't disabled notifications in the preferences screen.
 *
 * @param context Used to access utility methods and the ContentResolver
 *///from w w  w  .ja  va2  s .co m
synchronized public static void syncWeather(Context context) {

    try {
        /*
         * The getUrl method will return the URL that we need to get the forecast JSON for the
         * weather. It will decide whether to create a URL based off of the latitude and
         * longitude or off of a simple location as a String.
         */
        URL weatherRequestUrl = NetworkUtils.getUrl(context);

        /* Use the URL to retrieve the JSON */
        String jsonWeatherResponse = NetworkUtils.getResponseFromHttpUrl(weatherRequestUrl);

        /* Parse the JSON into a list of weather values */
        ContentValues[] weatherValues = OpenWeatherJsonUtils.getWeatherContentValuesFromJson(context,
                jsonWeatherResponse);

        /*
         * In cases where our JSON contained an error code, getWeatherContentValuesFromJson
         * would have returned null. We need to check for those cases here to prevent any
         * NullPointerExceptions being thrown. We also have no reason to insert fresh data if
         * there isn't any to insert.
         */
        if (weatherValues != null && weatherValues.length != 0) {
            /* Get a handle on the ContentResolver to delete and insert data */
            ContentResolver sunshineContentResolver = context.getContentResolver();

            /* Delete old weather data because we don't need to keep multiple days' data */
            sunshineContentResolver.delete(WeatherContract.WeatherEntry.CONTENT_URI, null, null);

            /* Insert our new weather data into Sunshine's ContentProvider */
            sunshineContentResolver.bulkInsert(WeatherContract.WeatherEntry.CONTENT_URI, weatherValues);

            /*
             * Finally, after we insert data into the ContentProvider, determine whether or not
             * we should notify the user that the weather has been refreshed.
             */
            boolean notificationsEnabled = SunshinePreferences.areNotificationsEnabled(context);

            /*
             * If the last notification was shown was more than 1 day ago, we want to send
             * another notification to the user that the weather has been updated. Remember,
             * it's important that you shouldn't spam your users with notifications.
             */
            long timeSinceLastNotification = SunshinePreferences.getEllapsedTimeSinceLastNotification(context);

            boolean oneDayPassedSinceLastNotification = false;

            if (timeSinceLastNotification >= DateUtils.DAY_IN_MILLIS) {
                oneDayPassedSinceLastNotification = true;
            }

            /*
             * We only want to show the notification if the user wants them shown and we
             * haven't shown a notification in the past day.
             */
            if (notificationsEnabled && oneDayPassedSinceLastNotification) {
                NotificationUtils.notifyUserOfNewWeather(context);
            }

            /* If the code reaches this point, we have successfully performed our sync */

        }

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }

    // Sync new weather data to Android Wear
    sendWearWeatherData(context);

}

From source file:com.rks.musicx.misc.utils.PlaylistHelper.java

/**
 * Delete playlist/*from ww w . j  a  v  a 2s .  c o m*/
 *
 * @param context
 * @param selectedplaylist
 */
public static void deletePlaylist(Context context, String selectedplaylist) {
    String playlistid = getPlayListId(context, selectedplaylist);
    ContentResolver resolver = context.getContentResolver();
    String where = MediaStore.Audio.Playlists._ID + "=?";
    String[] whereVal = { playlistid };
    resolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where, whereVal);
}

From source file:info.guardianproject.otr.app.im.app.DatabaseUtils.java

/** Clear the branding resource map cache. */
private static int clearBrandingResourceMapCache(ContentResolver cr, long providerId) {
    StringBuilder where = new StringBuilder();
    where.append(Imps.BrandingResourceMapCache.PROVIDER_ID);
    where.append('=');
    where.append(providerId);//from  w  w w .ja  va2 s.c om
    return cr.delete(Imps.BrandingResourceMapCache.CONTENT_URI, where.toString(), null);
}

From source file:com.silentcorp.autotracker.db.VehicleDB.java

/**
 * Delete vehicles TODO better sql query
 * //from   www  . j a  va 2  s.c om
 * @param resolver
 * @param ids
 */
public static void deleteVehicles(Context context, Set<Long> ids) {
    StringBuilder sb = new StringBuilder();
    String[] args = new String[ids.size()];

    Iterator<Long> iter = ids.iterator();
    int index = 0;
    while (iter.hasNext()) {
        Long id = iter.next();
        args[index] = Long.toString(id);
        index++;

        sb.append(COL_ID);
        sb.append(" = ?");
        if (iter.hasNext()) {
            sb.append(" OR ");
        }
    }

    // delete a vehicles records
    ContentResolver contentResolver = context.getContentResolver();
    contentResolver.delete(DBContentProvider.VEHICLES_URI, sb.toString(), args);

    //delete related events
    EventDB.deleteEventsByVehicleIDs(context, ids);

    //delete related notifications
    NotificationDB.deleteNotificationsByVehiclesIds(context, ids);
}

From source file:Main.java

public static void DeleteImageFromGalleryBase(final Context context, String fileName) {

    // Set up the projection (we only need the ID)
    String[] projection = { MediaStore.Images.Media._ID };

    // Match on the file path
    String selection = MediaStore.Images.Media.DATA + " = ?";
    String[] selectionArgs = new String[] { fileName };

    // Query for the ID of the media matching the file path
    Uri queryUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    ContentResolver contentResolver = context.getContentResolver();
    Cursor c = contentResolver.query(queryUri, projection, selection, selectionArgs, null);
    if (c.moveToFirst()) {
        // We found the ID. Deleting the item via the content provider will also remove the file
        long id = c.getLong(c.getColumnIndexOrThrow(MediaStore.Images.Media._ID));
        Uri deleteUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
        contentResolver.delete(deleteUri, null, null);
    } else {//  w w w  .j  a v  a 2 s  .c  om
        // File not found in media store DB
    }
    c.close();
}

From source file:saphion.batterycaster.providers.Alarm.java

public static boolean deleteAlarm(ContentResolver contentResolver, long alarmId) {
    if (alarmId == INVALID_ID)
        return false;
    int deletedRows = contentResolver.delete(getUri(alarmId), "", null);
    return deletedRows == 1;
}

From source file:com.slownet5.pgprootexplorer.utils.FileUtils.java

public static void removeMediaStore(Context context, File file) {
    try {//from  ww w  .ja  v  a2s.  co m
        final ContentResolver resolver = context.getContentResolver();

        // Remove media store entries for any files inside this directory, using
        // path prefix match. Logic borrowed from MtpDatabase.
        if (file.isDirectory()) {
            final String path = file.getAbsolutePath() + "/";
            resolver.delete(FILE_URI, "_data LIKE ?1 AND lower(substr(_data,1,?2))=lower(?3)",
                    new String[] { path + "%", Integer.toString(path.length()), path });
        }

        // Remove media store entry for this exact file.
        final String path = file.getAbsolutePath();
        resolver.delete(FILE_URI, "_data LIKE ?1 AND lower(_data)=lower(?2)", new String[] { path, path });
    } catch (Exception e) {
        e.printStackTrace();
    }
}

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

/**
 * Removes all data from themovies, thevideos, and thereviews tables.
 * @param context/*from   w w  w  . ja  v a  2  s  . c o  m*/
 */
public static void deleteFavorite(Context context, int movieId) {
    String[] whereArgs = new String[] { Integer.toString(movieId) };

    Log.e(TAG, "deleteFavorite");
    ContentResolver contentResolver = context.getContentResolver();
    int i = contentResolver.delete(TMDbContract.Movies.URI, TMDbContract.Movies.MOVIE_ID + " = ?", whereArgs);
    Log.e(TAG, "favorite movies deleted  " + i);

    contentResolver.delete(TMDbContract.Videos.URI, TMDbContract.Videos.MOVIE_IDS + " = ?", whereArgs);
    contentResolver.delete(TMDbContract.Reviews.URI, TMDbContract.Reviews.MOVIE_IDS + " = ?", whereArgs);
}

From source file:com.rks.musicx.misc.utils.PlaylistHelper.java

/**
 * Delete Playlist Track/*from  w w  w .  ja  va 2  s  .c  o m*/
 *
 * @param context
 * @param playlistId
 * @param audioId
 */
public static void deletePlaylistTrack(Context context, long playlistId, long audioId) {
    ContentResolver resolver = context.getContentResolver();
    Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    String filter = MediaStore.Audio.Playlists.Members.AUDIO_ID + " = " + audioId;
    resolver.delete(uri, filter, null);
}

From source file:org.voidsink.anewjkuapp.calendar.CalendarUtils.java

public static boolean removeCalendar(Context context, String name) {
    Account account = AppUtils.getAccount(context);
    if (account == null) {
        return true;
    }//from  w  w w .j ava2  s  . c o  m

    String id = getCalIDByName(context, account, name, false);
    if (id == null) {
        return true;
    }

    final ContentResolver resolver = context.getContentResolver();

    resolver.delete(
            KusssAuthenticator.asCalendarSyncAdapter(CalendarContractWrapper.Calendars.CONTENT_URI(),
                    account.name, account.type),
            CalendarContractWrapper.Calendars._ID() + "=?", new String[] { id });

    Log.i(TAG, String.format("calendar %s (id=%s) removed", name, id));

    return true;
}