android.content.ContentResolver#delete ( )源码实例Demo

下面列出了android.content.ContentResolver#delete ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: PADListener   文件: UpdateMonsterInfoHelper.java
private int saveData(List<MonsterInfoModel> monsters) {
	MyLog.entry();

	final ContentResolver cr = context.getContentResolver();
	final Uri uri = MonsterInfoDescriptor.UriHelper.uriForAll();

	cr.delete(uri, null, null);
	final ContentValues[] values = new ContentValues[monsters.size()];
	int i = 0;
	for (final MonsterInfoModel monster : monsters) {
		values[i] = MonsterInfoProviderHelper.modelToValues(monster);
		i++;
	}

	final int result = cr.bulkInsert(uri, values);
	MyLog.exit();
	return result;
}
 
源代码2 项目: VCL-Android   文件: Util.java
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static boolean deleteFile (String path){
    boolean deleted = false;
    path = Uri.decode(Strings.removeFileProtocole(path));
    //Delete from Android Medialib, for consistency with device MTP storing and other apps listing content:// media
    if (AndroidUtil.isHoneycombOrLater()){
        ContentResolver cr = VLCApplication.getAppContext().getContentResolver();
        String[] selectionArgs = { path };
        deleted = cr.delete(MediaStore.Files.getContentUri("external"),
                MediaStore.Files.FileColumns.DATA + "=?", selectionArgs) > 0;
    }
    File file = new File(path);
    if (file.exists())
        deleted |= file.delete();
    return deleted;
}
 
源代码3 项目: Zom-Android-XMPP   文件: Imps.java
public static int deleteMessageInDb(ContentResolver resolver, String id) {

        Uri.Builder builder = Messages.OTR_MESSAGES_CONTENT_URI_BY_PACKET_ID.buildUpon();
        builder.appendPath(id);

        int result = resolver.delete(builder.build(), null, null);
        if (result <= 0)
        {
            builder = Imps.Messages.CONTENT_URI_MESSAGES_BY_PACKET_ID.buildUpon();
            builder.appendPath(id);
            result = resolver.delete(builder.build(), null, null);
        }
        return result;
    }
 
源代码4 项目: Camera2   文件: VideoItem.java
@Override
public boolean delete()
{
    ContentResolver cr = mContext.getContentResolver();
    cr.delete(VideoDataQuery.CONTENT_URI,
            MediaStore.Video.VideoColumns._ID + "=" + mData.getContentId(), null);
    return super.delete();
}
 
源代码5 项目: Indic-Keyboard   文件: UserDictionarySettings.java
public static void deleteWord(final String word, final String shortcut,
        final ContentResolver resolver) {
    if (!IS_SHORTCUT_API_SUPPORTED) {
        resolver.delete(UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_SHORTCUT_UNSUPPORTED,
                new String[] { word });
    } else if (TextUtils.isEmpty(shortcut)) {
        resolver.delete(
                UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITHOUT_SHORTCUT,
                new String[] { word });
    } else {
        resolver.delete(
                UserDictionary.Words.CONTENT_URI, DELETE_SELECTION_WITH_SHORTCUT,
                new String[] { word, shortcut });
    }
}
 
源代码6 项目: squidb   文件: SqliteWrapper.java
public static int delete(Context context, ContentResolver resolver, Uri uri,
        String where, String[] selectionArgs) {
    try {
        return resolver.delete(uri, where, selectionArgs);
    } catch (SQLiteException e) {
        Log.e(TAG, "Catch a SQLiteException when delete: ", e);
        checkSQLiteException(context, e);
        return -1;
    }
}
 
源代码7 项目: Music-Player   文件: MusicUtil.java
public static void insertAlbumArt(@NonNull Context context, int albumId, String path) {
    ContentResolver contentResolver = context.getContentResolver();

    Uri artworkUri = Uri.parse("content://media/external/audio/albumart");
    contentResolver.delete(ContentUris.withAppendedId(artworkUri, albumId), null, null);

    ContentValues values = new ContentValues();
    values.put("album_id", albumId);
    values.put("_data", path);

    contentResolver.insert(artworkUri, values);
    contentResolver.notifyChange(artworkUri, null);
}
 
源代码8 项目: android-galaxyzoo   文件: Utils.java
public static void abandonItem(final Context context, final String itemId) {
    Log.info("abandonItem(): Abandoning item with itemId=" + itemId);

    final Uri itemUri = ContentUris.withAppendedId(
            Item.ITEMS_URI, Integer.parseInt(itemId));

    final ContentResolver resolver = context.getContentResolver();
    final int affected = resolver.delete(itemUri, null, null);
    if (affected != 1) {
        Log.error("abandonItem(): Unexpected number of rows affected: " + affected);
    }
}
 
源代码9 项目: Bop   文件: PlaylistUtils.java
public static void deletePlaylistTrack(Context context, String name, long audioId) {
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", Long.parseLong(getPlayListId(name)));
    final ContentResolver resolver = context.getContentResolver();
    resolver.delete(uri, MediaStore.Audio.Playlists.Members.AUDIO_ID + " = ? ", new String[]{
            Long.toString(audioId)
    });
    for (Playlist p :
            Main.data.playlists) {
        if (p.getName().equals(name)) {
            p.removeSong(audioId);
        }
    }
}
 
源代码10 项目: imsdk-android   文件: CalendarReminderUtils.java
/**
     * 删除日历事件
     */
    public static void deleteCalendarEvent(Context context,CalendarTrip.DataBean.TripsBean bean) {
        long checkEventID = checkEvents(context,bean);
        if(checkEventID<0){
            return;
        }
        ContentResolver cr = context.getContentResolver();
        ContentValues values = new ContentValues();
        Uri deleteUri = null;
        deleteUri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, checkEventID);
        int rows = cr.delete(deleteUri, null, null);
//        Log.i(DEBUG_TAG, "Rows deleted: " + rows);
    }
 
private void useContentProvider() {
    Random random = new Random();

    ContentResolver contentResolver = getContentResolver();

    ContentValues values = new ContentValues();

    // Insert first record
    values.put(DataContract.DATA, "Record_" + random.nextInt(Integer.MAX_VALUE));
    Uri firstRecordUri = contentResolver.insert(DataContract.CONTENT_URI, values);

    values.clear();

    // Insert second record
    values.put(DataContract.DATA, "Record_" + random.nextInt(Integer.MAX_VALUE));
    contentResolver.insert(DataContract.CONTENT_URI, values);

    values.clear();

    // Insert third record
    values.put(DataContract.DATA, "Record_" + random.nextInt(Integer.MAX_VALUE));
    contentResolver.insert(DataContract.CONTENT_URI, values);

    // Delete first record
    if (null != firstRecordUri) {
        contentResolver.delete(firstRecordUri, null, null);
    }

    // Create and set mCursor and list adapter
    mCursor = contentResolver.query(DataContract.CONTENT_URI, null, null, null,
            null);

    setListAdapter(new SimpleCursorAdapter(this, R.layout.list_layout, mCursor,
            DataContract.ALL_COLUMNS, new int[]{R.id.idString,
            R.id.data}, 0));
}
 
源代码12 项目: PowerFileExplorer   文件: FileUtil.java
/**
  * Delete a file. May be even on external SD card.
  *
  * @param file the file to be deleted.
  * @return True if successfully deleted.
  */
 static boolean deleteFile(@NonNull final File file, Context context) {
     // First try the normal deletion.
     if (file == null || !file.exists()) 
return true;
     if (file.delete() || deleteFilesInFolder(file, context))
         return true;

     // Try with Storage Access Framework.
     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && FileUtil.isOnExtSdCard(file, context)) {
         final DocumentFile document = getDocumentFile(file, false, context);
if (document != null) {
	return document.delete();
}
     }

     // Try the Kitkat workaround.
     if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
         final ContentResolver resolver = context.getContentResolver();

         try {
             final Uri uri = MediaStoreHack.getUriFromFile(file.getAbsolutePath(), context);
             resolver.delete(uri, null, null);
             return !file.exists();
         } catch (Exception e) {
             Log.e("AmazeFileUtils", "Error when deleting file " + file.getAbsolutePath(), e);
             return false;
         }
     }

     return !file.exists();
 }
 
源代码13 项目: Rey-MusicPlayer   文件: MusicUtils.java
public static void deletePlaylist(Context context, String playlistid) {
    ContentResolver resolver = context.getContentResolver();
    String where = MediaStore.Audio.Playlists._ID + "=?";
    String[] whereVal = {playlistid};
    resolver.delete(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, where, whereVal);
    return;
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
源代码15 项目: APlayer   文件: MediaStoreUtil.java
private static void deleteAlbumArt(@NonNull Context context, int albumId) {
  ContentResolver contentResolver = context.getContentResolver();
  Uri localUri = Uri.parse("content://media/external/audio/albumart");
  contentResolver.delete(ContentUris.withAppendedId(localUri, albumId), null, null);
}
 
源代码16 项目: android-dev-challenge   文件: 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
 */
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);
        }

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

    } catch (Exception e) {
        /* Server probably invalid */
        e.printStackTrace();
    }
}
 
源代码17 项目: android_9.0.0_r45   文件: CallLog.java
private static Uri addEntryAndRemoveExpiredEntries(Context context, UserManager userManager,
        UserHandle user, ContentValues values) {
    final ContentResolver resolver = context.getContentResolver();

    // Since we're doing this operation on behalf of an app, we only
    // want to use the actual "unlocked" state.
    final Uri uri = ContentProvider.maybeAddUserId(
            userManager.isUserUnlocked(user) ? CONTENT_URI : SHADOW_CONTENT_URI,
            user.getIdentifier());

    if (VERBOSE_LOG) {
        Log.v(LOG_TAG, String.format("Inserting to %s", uri));
    }

    try {
        // When cleaning up the call log, try to delete older call long entries on a per
        // PhoneAccount basis first.  There can be multiple ConnectionServices causing
        // the addition of entries in the call log.  With the introduction of Self-Managed
        // ConnectionServices, we want to ensure that a misbehaving self-managed CS cannot
        // spam the call log with its own entries, causing entries from Telephony to be
        // removed.
        final Uri result = resolver.insert(uri, values);
        if (values.containsKey(PHONE_ACCOUNT_ID)
                && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_ID))
                && values.containsKey(PHONE_ACCOUNT_COMPONENT_NAME)
                && !TextUtils.isEmpty(values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME))) {
            // Only purge entries for the same phone account.
            resolver.delete(uri, "_id IN " +
                    "(SELECT _id FROM calls"
                    + " WHERE " + PHONE_ACCOUNT_COMPONENT_NAME + " = ?"
                    + " AND " + PHONE_ACCOUNT_ID + " = ?"
                    + " ORDER BY " + DEFAULT_SORT_ORDER
                    + " LIMIT -1 OFFSET 500)", new String[] {
                    values.getAsString(PHONE_ACCOUNT_COMPONENT_NAME),
                    values.getAsString(PHONE_ACCOUNT_ID)
            });
        } else {
            // No valid phone account specified, so default to the old behavior.
            resolver.delete(uri, "_id IN " +
                    "(SELECT _id FROM calls ORDER BY " + DEFAULT_SORT_ORDER
                    + " LIMIT -1 OFFSET 500)", null);
        }

        return result;
    } catch (IllegalArgumentException e) {
        Log.w(LOG_TAG, "Failed to insert calllog", e);
        // Even though we make sure the target user is running and decrypted before calling
        // this method, there's a chance that the user just got shut down, in which case
        // we'll still get "IllegalArgumentException: Unknown URL content://call_log/calls".
        return null;
    }
}
 
/**
 * This test deletes all records from the weather table using the ContentProvider. It also
 * verifies that registered ContentObservers receive onChange callbacks when data is deleted.
 * <p>
 * It finally queries the ContentProvider to make sure that the table has been successfully
 * cleared.
 * <p>
 * NOTE: This does not delete the table itself. It just deletes the rows of data contained
 * within the table.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Within {@link WeatherProvider#delete(Uri, String, String[])}, you didn't call
 *    getContext().getContentResolver().notifyChange(uri, null) after performing a deletion.
 * <p>
 *   2) The cursor returned from the query was null
 * <p>
 *   3) After the attempted deletion, the ContentProvider still provided weather data
 */
@Test
public void testDeleteAllRecordsFromProvider() {

    /*
     * Ensure there are records to delete from the database. Due to our setUp method, the
     * database will not have any records in it prior to this method being run.
     */
    testBulkInsert();

    /*
     * TestContentObserver allows us to test weather or not notifyChange was called
     * appropriately. We will use that here to make sure that notifyChange is called when a
     * deletion occurs.
     */
    TestUtilities.TestContentObserver weatherObserver = TestUtilities.getTestContentObserver();

    /*
     * A ContentResolver provides us access to the content model. We can use it to perform
     * deletions and queries at our CONTENT_URI
     */
    ContentResolver contentResolver = mContext.getContentResolver();

    /* Register a content observer to be notified of changes to data at a given URI (weather) */
    contentResolver.registerContentObserver(
            /* URI that we would like to observe changes to */
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Whether or not to notify us if descendants of this URI change */
            true,
            /* The observer to register (that will receive notifyChange callbacks) */
            weatherObserver);

    /* Delete all of the rows of data from the weather table */
    contentResolver.delete(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null);

    /* Perform a query of the data that we've just deleted. This should be empty. */
    Cursor shouldBeEmptyCursor = contentResolver.query(
            WeatherContract.WeatherEntry.CONTENT_URI,
            /* Columns; leaving this null returns every column in the table */
            null,
            /* Optional specification for columns in the "where" clause above */
            null,
            /* Values for "where" clause */
            null,
            /* Sort order to return in Cursor */
            null);

    /*
     * If this fails, it's likely you didn't call notifyChange in your delete method from
     * your ContentProvider.
     */
    weatherObserver.waitForNotificationOrFail();

    /*
     * waitForNotificationOrFail is synchronous, so after that call, we are done observing
     * changes to content and should therefore unregister this observer.
     */
    contentResolver.unregisterContentObserver(weatherObserver);

    /* In some cases, the cursor can be null. That's actually a failure case here. */
    String cursorWasNull = "Cursor was null.";
    assertNotNull(cursorWasNull, shouldBeEmptyCursor);

    /* If the count of the cursor is not zero, all records weren't deleted */
    String allRecordsWereNotDeleted =
            "Error: All records were not deleted from weather table during delete";
    assertEquals(allRecordsWereNotDeleted,
            0,
            shouldBeEmptyCursor.getCount());

    /* Always close your cursor */
    shouldBeEmptyCursor.close();
}
 
/**
 * This method will insert the current Sales Detail Pending into a local database
 * so later can be query by {@link SalesPendingCheckoutDialogFragment}
 */
private void packTheCurrentSalesDetailPendingInToLocalDatabase() {

    // Delete all data in the local database before we insert new data
    final ContentResolver contentResolver = getActivity().getContentResolver();
    contentResolver.delete(ContractData.SalesDetailPendingEntry.CONTENT_URI, null, null);

    // Get the reference to ../SalesDetailPending/...
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference()
            .child(mUserUid).child(Constants.FIREBASE_SALES_DETAIL_PENDING_LOCATION);
    databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (!dataSnapshot.hasChildren()) {
                return;
            }

            // Iterate
            for (DataSnapshot snap : dataSnapshot.getChildren()) {

                // Initialize the content values
                ContentValues values = new ContentValues();

                // Initialize the model
                SalesDetailModel model = snap.getValue(SalesDetailModel.class);

                // Get the state
                String key = snap.getKey();
                String itemNumber = model.getItemNumber();
                String itemDesc = model.getItemDesc();
                String itemUnit = model.getItemUnit();
                String itemPrice = model.getItemPrice();
                String itemQty = model.getItemQuantity();
                String itemDiscount = model.getItemDiscount();
                String itemDiscountAmount = model.getItemDiscountAmout();
                String itemAmount = model.getItemAmount();

                // Pack into ContentValues object
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_PUSH_KEY, key);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_NUMBER, itemNumber);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DESC, itemDesc);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_UNIT, itemUnit);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_PRICE, itemPrice);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_QUANTITY, itemQty);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT, itemDiscount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_DISCOUNT_AMOUNT, itemDiscountAmount);
                values.put(ContractData.SalesDetailPendingEntry.COLUMN_ITEM_AMOUNT, itemAmount);


                // Insert into local database
                try {
                    contentResolver.insert(ContractData.SalesDetailPendingEntry.CONTENT_URI, values);
                } catch (Exception e) {
                    Log.e(TAG_LOG, e.getMessage());
                }
            }


        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e(TAG_LOG, databaseError.getMessage());
        }
    });

}
 
源代码20 项目: fdroidclient   文件: RepoProvider.java
public static void remove(Context context, long repoId) {
    purgeApps(context, findById(context, repoId));
    ContentResolver resolver = context.getContentResolver();
    Uri uri = RepoProvider.getContentUri(repoId);
    resolver.delete(uri, null, null);
}