簡體   English   中英

從外部存儲刪除圖像后刷新圖庫

[英]Refresh gallery after delete image from the external storage

我的問題是我要從外部存儲中刪除圖像,並且黑色占位符仍在那兒,指向已刪除的圖像位置。

這是代碼,請幫助我解決它。

提前致謝。

 String canonicalPath;
        try {
            canonicalPath = file.getCanonicalPath();
        } catch (IOException e) {
            canonicalPath = file.getAbsolutePath();
        }
        final Uri uri = MediaStore.Files.getContentUri("external");
        final int result = contentResolver.delete(uri,
                MediaStore.Files.FileColumns.DATA + "=?", new String[]{canonicalPath});
        if (result == 0) {
            final String absolutePath = file.getAbsolutePath();
            if (!absolutePath.equals(canonicalPath)) {
                contentResolver.delete(uri,
                        MediaStore.Files.FileColumns.DATA + "=?", new String[]{absolutePath});
            }
        }

我一直在我的音樂應用程序中使用此功能,但也應該適用於畫廊。 這首先找到所需條目的_id ,然后構建正確的uri提交給刪除查詢。

public void deleteFromMediaStore(String pathToDelete, Context context) {
    ContentResolver contentResolver = context.getContentResolver();
    if (contentResolver != null) {
        Cursor matchingIndex = contentResolver.query(Media.EXTERNAL_CONTENT_URI, new String[]{"_id", "_data"}, "_data=?", new String[]{pathToDelete}, null);

        if(matchingIndex != null && matchingIndex.getCount() > 0) {
            matchingIndex.moveToFirst();
            while (!matchingIndex.isAfterLast()) {
                context.getContentResolver().delete(ContentUris.withAppendedId(Media.EXTERNAL_CONTENT_URI, (long) matchingIndex.getInt(matchingIndex.getColumnIndex("_id"))), null, null);
                matchingIndex.moveToNext();
            }
            matchingIndex.close();
        }
    }
}

您可以發送廣播

Intent intent =
      new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(file));
sendBroadcast(intent);

或者如果您想回調

MediaScannerConnection.scanFile(
      getApplicationContext(),
      new String[]{file.getAbsolutePath()},
      null,
      new OnScanCompletedListener() {
         @Override
         public void onScanCompleted(String path, Uri uri) {

         }
      });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM