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:org.mariotaku.twidere.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();//  ww w .  j  a  va2 s. co  m
    final ContentResolver resolver = context.getContentResolver();
    final boolean large_profile_image = context.getResources().getBoolean(R.bool.hires_profile_image);
    resolver.delete(CachedStatuses.CONTENT_URI, where, null);
    resolver.insert(CachedStatuses.CONTENT_URI,
            makeStatusContentValues(status, account_id, large_profile_image));
    return new ParcelableStatus(status, account_id, false, large_profile_image, true);
}

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

private void parseDeleteMessage(XboxLiveAccount account, long messageUid) throws IOException, ParserException {
    String token = getVToken(String.format(URL_VTOKEN_MESSAGES, mLocale));

    String url = String.format(URL_JSON_DELETE_MESSAGE, mLocale);

    List<NameValuePair> inputs = new ArrayList<NameValuePair>(3);

    // Message ID
    addValue(inputs, "msgID", messageUid);

    // Req. ver. token
    addValue(inputs, "__RequestVerificationToken", token);

    String page = getResponse(url, inputs, true);

    long started = System.currentTimeMillis();

    JSONObject json = getJSONObject(page, false);

    try {/*from  w  w  w . j a v a  2s  .  c  o m*/
        if (!json.getBoolean("Success")) {
            if (App.getConfig().logToConsole())
                App.logv("XboxLiveParser/parseDeleteMessage: Parser error: " + page);

            throw new ParserException(
                    json.optString("Status", mContext.getString(R.string.message_could_not_be_deleted)));
        }
    } catch (JSONException e) {
        if (App.getConfig().logToConsole()) {
            App.logv("XboxLiveParser/parseDeleteMessage: JSON error: " + page);
            e.printStackTrace();
        }
    }

    ContentResolver cr = mContext.getContentResolver();
    int rows = cr.delete(Messages.CONTENT_URI,
            Messages.UID + "=" + messageUid + " AND " + Messages.ACCOUNT_ID + "=" + account.getId(), null);

    if (rows > 0)
        cr.notifyChange(Messages.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        displayTimeTaken("Message deletion processing", started);
}

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

private void parseBlockMessage(XboxLiveAccount account, long messageUid) throws IOException, ParserException {
    String token = getVToken(String.format(URL_VTOKEN_MESSAGES, mLocale));

    String url = String.format(URL_JSON_BLOCK_MESSAGE, mLocale);

    List<NameValuePair> inputs = new ArrayList<NameValuePair>(3);

    // Message ID
    addValue(inputs, "msgID", messageUid);

    // Req. ver. token
    addValue(inputs, "__RequestVerificationToken", getVToken(token));

    String page = getResponse(url, inputs, true);

    long started = System.currentTimeMillis();

    JSONObject json = getJSONObject(page, false);

    try {/*from   w w  w.  j  ava2s  .c  o m*/
        if (!json.getBoolean("Success")) {
            if (App.getConfig().logToConsole())
                App.logv("XboxLiveParser/parseBlockMessage: Parser error: " + page);

            throw new ParserException(
                    json.optString("Status", mContext.getString(R.string.sender_not_blocked)));
        }
    } catch (JSONException e) {
        if (App.getConfig().logToConsole()) {
            App.logv("XboxLiveParser/parseDeleteMessage: JSON error: " + page);
            e.printStackTrace();
        }
    }

    ContentResolver cr = mContext.getContentResolver();
    int rows = cr.delete(Messages.CONTENT_URI,
            Messages.UID + "=" + messageUid + " AND " + Messages.ACCOUNT_ID + "=" + account.getId(), null);

    if (rows > 0)
        cr.notifyChange(Messages.CONTENT_URI, null);

    if (App.getConfig().logToConsole())
        displayTimeTaken("Message deletion processing", started);
}

From source file:com.android.exchange.SyncManager.java

/**
 * Compare our account list (obtained from EmailProvider) with the account list owned by
 * AccountManager.  If there are any orphans (an account in one list without a corresponding
 * account in the other list), delete the orphan, as these must remain in sync.
 *
 * Note that the duplication of account information is caused by the Email application's
 * incomplete integration with AccountManager.
 *
 * This function may not be called from the main/UI thread, because it makes blocking calls
 * into the account manager./*from   w  w  w  .j  a  v a 2  s.c o m*/
 *
 * @param context The context in which to operate
 * @param cachedEasAccounts the exchange provider accounts to work from
 * @param accountManagerAccounts The account manager accounts to work from
 * @param blockExternalChanges FOR TESTING ONLY - block backups, security changes, etc.
 * @param resolver the content resolver for making provider updates (injected for testability)
 */
/* package */ static void reconcileAccountsWithAccountManager(Context context, List<Account> cachedEasAccounts,
        android.accounts.Account[] accountManagerAccounts, boolean blockExternalChanges,
        ContentResolver resolver) {
    // First, look through our cached EAS Accounts (from EmailProvider) to make sure there's a
    // corresponding AccountManager account
    boolean accountsDeleted = false;
    for (Account providerAccount : cachedEasAccounts) {
        String providerAccountName = providerAccount.mEmailAddress;
        boolean found = false;
        for (android.accounts.Account accountManagerAccount : accountManagerAccounts) {
            if (accountManagerAccount.name.equalsIgnoreCase(providerAccountName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            if ((providerAccount.mFlags & Account.FLAGS_INCOMPLETE) != 0) {
                log("Account reconciler noticed incomplete account; ignoring");
                continue;
            }
            // This account has been deleted in the AccountManager!
            alwaysLog("Account deleted in AccountManager; deleting from provider: " + providerAccountName);
            // TODO This will orphan downloaded attachments; need to handle this
            resolver.delete(ContentUris.withAppendedId(Account.CONTENT_URI, providerAccount.mId), null, null);
            accountsDeleted = true;
        }
    }
    // Now, look through AccountManager accounts to make sure we have a corresponding cached EAS
    // account from EmailProvider
    for (android.accounts.Account accountManagerAccount : accountManagerAccounts) {
        String accountManagerAccountName = accountManagerAccount.name;
        boolean found = false;
        for (Account cachedEasAccount : cachedEasAccounts) {
            if (cachedEasAccount.mEmailAddress.equalsIgnoreCase(accountManagerAccountName)) {
                found = true;
            }
        }
        if (!found) {
            // This account has been deleted from the EmailProvider database
            alwaysLog("Account deleted from provider; deleting from AccountManager: "
                    + accountManagerAccountName);
            // Delete the account
            AccountManagerFuture<Boolean> blockingResult = AccountManager.get(context)
                    .removeAccount(accountManagerAccount, null, null);
            try {
                // Note: All of the potential errors from removeAccount() are simply logged
                // here, as there is nothing to actually do about them.
                blockingResult.getResult();
            } catch (OperationCanceledException e) {
                Log.w(Email.LOG_TAG, e.toString());
            } catch (AuthenticatorException e) {
                Log.w(Email.LOG_TAG, e.toString());
            } catch (IOException e) {
                Log.w(Email.LOG_TAG, e.toString());
            }
            accountsDeleted = true;
        }
    }
    // If we changed the list of accounts, refresh the backup & security settings
    if (!blockExternalChanges && accountsDeleted) {
        AccountBackupRestore.backupAccounts(context);
        SecurityPolicy.getInstance(context).reducePolicies();
        Email.setNotifyUiAccountsChanged(true);
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Stores an image in the gallery. This is a fixed version that stores
 * correct DATE_TAKEN so that the ordering of remains correct.
 * //  ww w .jav  a2  s .c  o m
 * @see android.provider.MediaStore.Images.Media#insertImage(ContentResolver,
 *      Bitmap, String, String)
 */
public static final String insertImage(ContentResolver contentResolver, Bitmap bitmap, String title,
        String description) {

    final int SAVEQUALITY = 100;

    ContentValues values = new ContentValues();
    values.put(Images.Media.TITLE, title);
    values.put(Images.Media.DISPLAY_NAME, title);
    values.put(Images.Media.DESCRIPTION, description);
    values.put(Images.Media.MIME_TYPE, "image/jpeg");
    // Fix
    values.put(Images.Media.DATE_ADDED, System.currentTimeMillis());
    values.put(Images.Media.DATE_TAKEN, System.currentTimeMillis());

    Uri url = null;
    String returnValue = null;
    boolean ok = false;

    try {
        url = contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

        if (bitmap != null) {
            OutputStream outputStream = contentResolver.openOutputStream(url);
            try {
                bitmap.compress(Bitmap.CompressFormat.JPEG, SAVEQUALITY, outputStream);
                ok = true;
            } catch (Exception e) {
                // ignore
            }
            outputStream.close();
        }
    } catch (Exception e) {
        // ignore
    }

    if (!ok) {
        // If something went wrong, delete the entry
        if (url != null) {
            contentResolver.delete(url, null, null);
            url = null;
        }
    }

    if (url != null) {
        returnValue = url.toString();
    }

    return returnValue;
}

From source file:mp.teardrop.PlaybackService.java

/**
 * Delete all the songs in the given media set. Should be run on a
 * background thread.//from   w w  w  . j  a v  a 2s.  c  om
 *
 * @param type One of the TYPE_* constants, excluding playlists.
 * @param id The MediaStore id of the media to delete.
 * @return The number of songs deleted.
 */
public int deleteMedia(int type, long id) {
    int count = 0;

    ContentResolver resolver = getContentResolver();
    String[] projection = new String[] { MediaStore.Audio.Media._ID, MediaStore.Audio.Media.DATA };
    Cursor cursor = MediaUtils.buildQuery(type, id, projection, null).runQuery(resolver);

    if (cursor != null) {
        while (cursor.moveToNext()) {
            if (new File(cursor.getString(1)).delete()) {
                long songId = cursor.getLong(0);
                String where = MediaStore.Audio.Media._ID + '=' + songId;
                resolver.delete(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, where, null);
                mTimeline.removeSong(songId);
                ++count;
            }
        }

        cursor.close();
    }

    return count;
}

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

private void parseFriends(XboxLiveAccount account) throws IOException, ParserException {
    long started = System.currentTimeMillis();
    long updated = System.currentTimeMillis();
    long accountId = account.getId();

    synchronized (XboxLiveParser.class) {
        String token = getVToken(String.format(URL_VTOKEN_FRIENDS, mLocale));

        String url = String.format(URL_JSON_FRIEND_LIST, mLocale);

        List<NameValuePair> inputs = new ArrayList<NameValuePair>(3);
        addValue(inputs, "__RequestVerificationToken", token);

        String page = getResponse(url, inputs, true);
        JSONObject data = getXboxJsonObject(page);

        if (data == null)
            throw new ParserException(mContext, R.string.error_friend_retrieval);

        ContentResolver cr = mContext.getContentResolver();
        List<ContentValues> newCvs = new ArrayList<ContentValues>(100);

        parseFriendSection(accountId, data.optJSONArray("Friends"), updated, newCvs, -1);
        parseFriendSection(accountId, data.optJSONArray("Incoming"), updated, newCvs,
                XboxLive.STATUS_INVITE_RCVD);
        parseFriendSection(accountId, data.optJSONArray("Outgoing"), updated, newCvs,
                XboxLive.STATUS_INVITE_SENT);

        // Remove friends that are missing from list
        cr.delete(Friends.CONTENT_URI,
                Friends.DELETE_MARKER + "!=" + updated + " AND " + Friends.ACCOUNT_ID + "=" + accountId, null);

        if (newCvs.size() > 0) {
            ContentValues[] cvs = new ContentValues[newCvs.size()];
            newCvs.toArray(cvs);// w w  w.  j a v  a 2 s.co m

            cr.bulkInsert(Friends.CONTENT_URI, cvs);

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

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

        // A friend list is very likely to change at every sync, so
        // we just do it no matter what
        cr.notifyChange(Friends.CONTENT_URI, null);
    }

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

From source file:com.bt.download.android.gui.Librarian.java

private void syncApplicationsProviderSupport() {
    try {//ww w  . j a va  2 s. c o m

        List<FileDescriptor> fds = Librarian.instance().getFiles(Constants.FILE_TYPE_APPLICATIONS, 0,
                Integer.MAX_VALUE, false);

        int packagesSize = fds.size();
        String[] packages = new String[packagesSize];
        for (int i = 0; i < packagesSize; i++) {
            packages[i] = fds.get(i).album;
        }
        Arrays.sort(packages);

        List<ApplicationInfo> applications = context.getPackageManager().getInstalledApplications(0);

        int size = applications.size();

        ArrayList<String> newPackagesList = new ArrayList<String>(size);

        for (int i = 0; i < size; i++) {
            ApplicationInfo appInfo = applications.get(i);

            try {
                if (appInfo == null) {
                    continue;
                }

                newPackagesList.add(appInfo.packageName);

                File f = new File(appInfo.sourceDir);
                if (!f.canRead()) {
                    continue;
                }

                int index = Arrays.binarySearch(packages, appInfo.packageName);
                if (index >= 0) {
                    continue;
                }

                String data = appInfo.sourceDir;
                String title = appInfo.packageName;
                String packageName = appInfo.packageName;
                String version = "";

                Apk apk = new Apk(context, appInfo.sourceDir);
                String[] result = parseApk(apk);
                if (result != null) {
                    if (result[1] == null) {
                        continue;
                    }
                    title = result[1];
                    version = result[0];
                }

                ContentValues cv = new ContentValues();
                cv.put(ApplicationsColumns.DATA, data);
                cv.put(ApplicationsColumns.SIZE, f.length());
                cv.put(ApplicationsColumns.TITLE, title);
                cv.put(ApplicationsColumns.MIME_TYPE, Constants.MIME_TYPE_ANDROID_PACKAGE_ARCHIVE);
                cv.put(ApplicationsColumns.VERSION, version);
                cv.put(ApplicationsColumns.PACKAGE_NAME, packageName);

                ContentResolver cr = context.getContentResolver();

                Uri uri = cr.insert(Applications.Media.CONTENT_URI, cv);

                if (appInfo.icon != 0) {
                    try {
                        InputStream is = null;
                        OutputStream os = null;

                        try {
                            is = apk.openRawResource(appInfo.icon);
                            os = cr.openOutputStream(uri);

                            byte[] buff = new byte[4 * 1024];
                            int n = 0;
                            while ((n = is.read(buff, 0, buff.length)) != -1) {
                                os.write(buff, 0, n);
                            }

                        } finally {
                            if (os != null) {
                                os.close();
                            }
                            if (is != null) {
                                is.close();
                            }
                        }
                    } catch (Throwable e) {
                        Log.e(TAG, "Can't retrieve icon image for application " + appInfo.packageName);
                    }
                }
            } catch (Throwable e) {
                Log.e(TAG, "Error retrieving information for application " + appInfo.packageName);
            }
        }

        // clean uninstalled applications
        String[] newPackages = newPackagesList.toArray(new String[0]);
        Arrays.sort(newPackages);

        // simple way n * log(n)
        for (int i = 0; i < packagesSize; i++) {
            String packageName = packages[i];
            if (Arrays.binarySearch(newPackages, packageName) < 0) {
                ContentResolver cr = context.getContentResolver();
                cr.delete(Applications.Media.CONTENT_URI,
                        ApplicationsColumns.PACKAGE_NAME + " LIKE '%" + packageName + "%'", null);
            }
        }

    } catch (Throwable e) {
        Log.e(TAG, "Error performing initial applications provider synchronization with device", e);
    }
}

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

@Override
public void deleteAccount(BasicAccount account) {
    ContentResolver cr = mContext.getContentResolver();
    long accountId = account.getId();

    // Clear games & achievements
    Cursor c = cr.query(Games.CONTENT_URI, new String[] { Games._ID }, Games.ACCOUNT_ID + "=" + accountId, null,
            null);/*from  ww w.  java2  s.c o m*/

    if (c != null) {
        StringBuffer buffer = new StringBuffer();

        try {
            while (c.moveToNext()) {
                if (buffer.length() > 0)
                    buffer.append(",");
                buffer.append(c.getLong(0));
            }

            if (buffer.length() > 0) {
                // Clear achievements
                cr.delete(Achievements.CONTENT_URI, Achievements.GAME_ID + " IN (" + buffer.toString() + ")",
                        null);
            }
        } catch (Exception e) {
            // Do nothing
        } finally {
            c.close();
        }
    }

    try {
        // Clear games
        cr.delete(Games.CONTENT_URI, Games.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete friends
        cr.delete(Friends.CONTENT_URI, Friends.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete messages
        cr.delete(Messages.CONTENT_URI, Messages.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete sent messages
        cr.delete(SentMessages.CONTENT_URI, SentMessages.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete beacons
        cr.delete(Beacons.CONTENT_URI, Beacons.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete profiles
        cr.delete(Profiles.CONTENT_URI, Profiles.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete notify states
        cr.delete(NotifyStates.CONTENT_URI, Profiles.ACCOUNT_ID + "=" + accountId, null);
    } catch (Exception e) {
        // Do nothing
    }

    try {
        // Delete authenticated session
        deleteSession(account);
    } catch (Exception e) {
        // Do nothing
    }

    // Send notifications
    cr.notifyChange(Achievements.CONTENT_URI, null);
    cr.notifyChange(Games.CONTENT_URI, null);
    cr.notifyChange(Friends.CONTENT_URI, null);
    cr.notifyChange(Messages.CONTENT_URI, null);
    cr.notifyChange(Profiles.CONTENT_URI, null);
    cr.notifyChange(Beacons.CONTENT_URI, null);
    cr.notifyChange(SentMessages.CONTENT_URI, null);
    cr.notifyChange(NotifyStates.CONTENT_URI, null);

}