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:ch.berta.fabio.popularmovies.data.repositories.MovieRepositoryImpl.java

@Override
public Observable<Integer> deleteMovieLocal(@NonNull final Context context, long movieRowId) {
    return Observable.just(movieRowId).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .map(new Func1<Long, Integer>() {
                @Override//from   w w w.  j a va  2 s  . co  m
                public Integer call(Long aLong) {
                    final ContentResolver contentResolver = context.getApplicationContext()
                            .getContentResolver();
                    return contentResolver.delete(MovieContract.Movie.buildMovieUri(aLong), null, null);
                }
            });
}

From source file:org.ale.scanner.zotero.web.zotero.ZoteroHandler.java

private void handlePermissions(final String xml) {
    final ContentResolver cr = APIHandler.MAIN.getContentResolver();
    final Account user = APIHandler.MAIN.getUserAccount();

    new Thread(new Runnable() {
        public void run() {
            final Access perms = ZoteroAPIClient.parsePermissions(xml, user);
            if (perms != null) {
                cr.delete(Database.ACCESS_URI, Access.COL_ACCT + "=?",
                        new String[] { String.valueOf(user.getDbId()) });
                perms.writeToDB(cr);//  w ww. j  a  v  a  2  s  .c  o m

                checkActivityAndRun(new Runnable() {
                    public void run() {
                        APIHandler.MAIN.postAccountPermissions(perms);
                    }
                });
            } else {
                // TODO: Garbled XML? Tell the user
            }
        }
    }).start();
}

From source file:com.noshufou.android.su.AppDetailsFragment.java

public void forget(View view) {
    if (!mReady) {
        return;//  w ww .jav a2  s. c  om
    }

    ContentResolver cr = getActivity().getContentResolver();
    Uri uri = Uri.withAppendedPath(Apps.CONTENT_URI, String.valueOf(mShownIndex));

    cr.delete(uri, null, null);
    closeDetails();
}

From source file:net.niyonkuru.koodroid.service.SessionService.java

private void logout() {
    final ContentResolver cr = getContentResolver();
    final String email = mSettings.email();

    /* clear application settings */
    cr.delete(Settings.CONTENT_URI, null, null);

    try {/*from   w  w w.java  2s. c  om*/
        /* allow a 5 second window for batch operations to finish */
        Thread.sleep(5 * DateUtils.SECOND_IN_MILLIS);
    } catch (InterruptedException ignored) {
    }
    /* clear database data */
    cr.delete(Subscribers.CONTENT_URI, Subscribers.SUBSCRIBER_EMAIL + "='" + email + "'", null);

    CookieManager cookieManager = CookieManager.getInstance();
    if (cookieManager != null) {
        cookieManager.removeAllCookie();
    }

    stopSelf();
}

From source file:com.andrew.apollo.utils.MusicUtils.java

/**
 * Removes a single track from a given playlist
 * @param context The {@link Context} to use.
 * @param id The id of the song to remove.
 * @param playlistId The id of the playlist being removed from.
 * @param showNotification if true shows a notification at the top.
 *///from  w ww .  j  a  v  a 2  s .c om
public static void removeFromPlaylist(final Context context, final long id, final long playlistId,
        boolean showNotification) {
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistId);
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(uri, Playlists.Members.AUDIO_ID + " = ? ", new String[] { Long.toString(id) });

    if (showNotification) {
        try {
            final String message = context.getResources().getQuantityString(R.plurals.NNNtracksfromplaylist, 1,
                    1);
            AppMsg.makeText(context, message, AppMsg.STYLE_CONFIRM).show();
        } catch (Throwable t) {
            // java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
        }
    }
}

From source file:com.antew.redditinpictures.library.ui.base.BaseFragmentActivityWithMenu.java

protected void deleteSubreddit(String subredditName) {
    // If the user isn't logged in we don't care about subscribing/unsubscribing
    if (!RedditLoginInformation.isLoggedIn()) {
        RedditService.unsubscribe(this, subredditName);
    }//from  w w  w.  j a v  a 2 s.c  om
    ContentResolver resolver = getContentResolver();
    resolver.delete(RedditContract.Subreddits.CONTENT_URI, RedditContract.SubredditColumns.NAME + " = ?",
            new String[] { subredditName });
}

From source file:info.guardianproject.notepadbot.NoteCipher.java

private void handleDelete() {
    if (mCacheWord.isLocked()) {
        return;// www.  j  av  a2  s  .  co m
    }
    final AlertDialog.Builder b = new AlertDialog.Builder(this);
    b.setIcon(android.R.drawable.ic_dialog_alert);
    b.setTitle(R.string.app_name);
    b.setMessage(R.string.confirm_delete);
    b.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {

            // User clicked OK so go ahead and delete
            ContentResolver cr = getContentResolver();

            if (cr != null)
                cr.delete(dataStream, null, null);
            else {
                Toast.makeText(NoteCipher.this, R.string.unable_to_delete_original, Toast.LENGTH_SHORT).show();
            }

        }
    });
    b.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int whichButton) {

        }
    });
    b.show();
}

From source file:org.jsharkey.sky.WebserviceHelper.java

/**
 * Perform a webservice query to retrieve and store the forecast for the
 * given widget. This call blocks until request is finished and
 * {@link Forecasts#CONTENT_URI} has been updated.
 *///from   w  w w  . j  a  v a2  s . c  o  m
public static void updateForecasts(Context context, Uri appWidgetUri, int days) throws ForecastParseException {

    Uri appWidgetForecasts = Uri.withAppendedPath(appWidgetUri, AppWidgets.TWIG_FORECASTS);

    ContentResolver resolver = context.getContentResolver();

    Cursor cursor = null;
    double lat = Double.NaN;
    double lon = Double.NaN;

    // Pull exact forecast location from database
    try {
        cursor = resolver.query(appWidgetUri, PROJECTION_APPWIDGET, null, null, null);
        if (cursor != null && cursor.moveToFirst()) {
            lat = cursor.getDouble(COL_LAT);
            lon = cursor.getDouble(COL_LON);
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    // Query webservice for this location
    List<Forecast> forecasts = queryLocation(lat, lon, days);

    if (forecasts == null || forecasts.size() == 0) {
        throw new ForecastParseException("No forecasts found from webservice query");
    }

    // Purge existing forecasts covered by incoming data, and anything
    // before today
    long lastMidnight = ForecastUtils.getLastMidnight();
    long earliest = Long.MAX_VALUE;
    for (Forecast forecast : forecasts) {
        earliest = Math.min(earliest, forecast.validStart);
    }

    resolver.delete(appWidgetForecasts, ForecastsColumns.VALID_START + " >= " + earliest + " OR "
            + ForecastsColumns.VALID_START + " <= " + lastMidnight, null);

    // Insert any new forecasts found
    ContentValues values = new ContentValues();
    for (Forecast forecast : forecasts) {
        Log.d(TAG, "inserting forecast with validStart=" + forecast.validStart);
        values.clear();
        values.put(ForecastsColumns.VALID_START, forecast.validStart);
        values.put(ForecastsColumns.TEMP_HIGH, forecast.tempHigh);
        values.put(ForecastsColumns.TEMP_LOW, forecast.tempLow);
        values.put(ForecastsColumns.CONDITIONS, forecast.conditions);
        values.put(ForecastsColumns.URL, forecast.url);
        if (forecast.alert) {
            values.put(ForecastsColumns.ALERT, ForecastsColumns.ALERT_TRUE);
        }
        resolver.insert(appWidgetForecasts, values);
    }

    // Mark widget cache as being updated
    values.clear();
    values.put(AppWidgetsColumns.LAST_UPDATED, System.currentTimeMillis());
    resolver.update(appWidgetUri, values, null, null);
}

From source file:com.frostwire.android.gui.Librarian.java

/**
 * Deletes files.//w  w w . java  2s. c o m
 * If the fileType is audio it'll use MusicUtils.deleteTracks and
 * tell apollo to clean everything there, playslists, recents, etc.
 *
 * @param context
 * @param fileType
 * @param fds
 */
public void deleteFiles(final Context context, byte fileType, Collection<FileDescriptor> fds) {
    List<Integer> ids = new ArrayList<>(fds.size());
    final int audioMediaType = MediaType.getAudioMediaType().getId();
    if (fileType == audioMediaType) {
        ArrayList<Long> trackIdsToDelete = new ArrayList<>();
        for (FileDescriptor fd : fds) {
            // just in case, as we had similar checks in other code
            if (fd.fileType == audioMediaType) {
                trackIdsToDelete.add((long) fd.id);
                ids.add(fd.id);
            }
        }
        // wish I could do just trackIdsToDelete.toArray(new long[0]) ...
        long[] songsArray = new long[trackIdsToDelete.size()];
        int i = 0;
        for (Long l : trackIdsToDelete) {
            songsArray[i++] = l;
        }
        try {
            MusicUtils.deleteTracks(context, songsArray, false);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    } else {
        for (FileDescriptor fd : fds) {
            ids.add(fd.id);
        }
    }

    try {
        if (context != null) {
            ContentResolver cr = context.getContentResolver();
            TableFetcher fetcher = TableFetchers.getFetcher(fileType);
            cr.delete(fetcher.getContentUri(), MediaColumns._ID + " IN " + buildSet(ids), null);
        } else {
            Log.e(TAG, "Failed to delete files from media store, no context available");
        }
    } catch (Throwable e) {
        Log.e(TAG, "Failed to delete files from media store", e);
    }

    FileSystem fs = Platforms.fileSystem();
    for (FileDescriptor fd : fds) {
        try {
            fs.delete(new File(fd.filePath));
        } catch (Throwable ignored) {
        }
    }

    UIUtils.broadcastAction(context, Constants.ACTION_FILE_ADDED_OR_REMOVED,
            new UIUtils.IntentByteExtra(Constants.EXTRA_REFRESH_FILE_TYPE, fileType));
}

From source file:com.murrayc.galaxyzoo.app.syncadapter.SyncAdapter.java

private void removeItem(final String itemId) {
    final ContentResolver resolver = getContentResolver();

    //ItemsContentProvider takes care of deleting related files, classification answers, etc:
    if (resolver.delete(Utils.getItemUri(itemId), null, null) < 1) {
        Log.error("removeItem(): No item rows were removed.");
    }/*from  ww  w.j a va2 s  .  co m*/
}