Delete a file in Android when you have a path of form `/storage/1018-2710/Pictures/oLvCVPZrNxk.jpg`

huangapple go评论67阅读模式
英文:

Delete a file in Android when you have a path of form `/storage/1018-2710/Pictures/oLvCVPZrNxk.jpg`

问题

我正在尝试从Android外部存储中删除文件,问题是,我已经尝试多次以多种不同的方式获取路径。使用MediaStore Api,我已经非常接近了,但是无法弄清楚如何做到这一点。
我无法获取EXTERNAL_URI,因为投影需要字符串,而MediaStore上的EXTERNAL_URI返回的是URI而不是字符串。

这是我加载图像的方式,GalleryImage类只包含文件路径/storage/1018-2710/Pictures/oLvCVPZrNxk.jpg,以及一些处理选择的布尔值。我尝试添加外部URI,但未能成功。

public class ImageLoader {
    public ArrayList<GalleryImage> getAllShownImagesPath(Context context) {
        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name, column_index_content_uri;
        ArrayList<GalleryImage> listOfAllImages = new ArrayList<GalleryImage>();
        String absolutePathOfImage = null;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = { MediaStore.MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
        };

        cursor = context.getContentResolver().query(uri, projection, null,
                null, null);

        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);
         //   String externalURI = cursor.getString();
            String externalURI = ""; //empty,  beacuse I couldnt get it to work...

            listOfAllImages.add(new GalleryImage(false, false , absolutePathOfImage, externalURI));
        }

        cursor.close();

        return listOfAllImages;
    }
}

这是我在片段中尝试删除图像的地方

if(item.getItemId() == R.id.delete_selected){
    //Uri root = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    String root = Environment.getExternalStorageDirectory().toString();
    for(GalleryImage i : mViewModel.selectedImages){
        File file = new File(root + i.getmImageUrl());
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("file Deleted :" + file.getPath());
            } else {
                System.out.println("file not Deleted :" + file.getPath());
            }
        }
    }
}

我尝试了4、5种不同的组合,但似乎没有一个有效,我试图获取图像的正确路径,我看到可能使用EXTERNAL_URI可能是一种方法,但我不知道如何将其放入我的GalleryImage中。非常感谢您的帮助!

英文:

So I am trying to delete a file from Android External storage, the problem is, I've tried getting the path multiple times in multiple different ways. Using MediaStore Api I've come really close but cannot figure out how to do it.
I cannot get the EXTERNAL_URI because the projection requires Strings and EXTERNAL_URI on MediaStore returns a URI not a String.

This is how I load images, the GalleryImage class just contains, file path /storage/1018-2710/Pictures/oLvCVPZrNxk.jpg, and some booleans to handle selection. I tried adding external URI but failed to do so.

public class ImageLoader {
    public ArrayList&lt;GalleryImage&gt; getAllShownImagesPath(Context context) {
        Uri uri;
        Cursor cursor;
        int column_index_data, column_index_folder_name, column_index_content_uri;
        ArrayList&lt;GalleryImage&gt; listOfAllImages = new ArrayList&lt;GalleryImage&gt;();
        String absolutePathOfImage = null;
        uri = android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String[] projection = { MediaStore.MediaColumns.DATA,
                MediaStore.Images.Media.BUCKET_DISPLAY_NAME,
        };

        cursor = context.getContentResolver().query(uri, projection, null,
                null, null);

        column_index_data = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
        column_index_folder_name = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.BUCKET_DISPLAY_NAME);

        while (cursor.moveToNext()) {
            absolutePathOfImage = cursor.getString(column_index_data);
         //   String externalURI = cursor.getString();
            String externalURI = &quot;&quot;; //empty,  beacuse I couldnt get it to work...

            listOfAllImages.add(new GalleryImage(false, false , absolutePathOfImage, externalURI));
        }


        cursor.close();

        return listOfAllImages;
    }
}

And here in my fragment is where I am trying to delete the Images

 if(item.getItemId() == R.id.delete_selected){
                    //Uri root = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                    String root = Environment.getExternalStorageDirectory().toString();
                    for(GalleryImage i : mViewModel.selectedImages){
                        File file = new File(root + i.getmImageUrl());
                        if (file.exists()) {
                            if (file.delete()) {
                                System.out.println(&quot;file Deleted :&quot; + file.getPath());
                            } else {
                                System.out.println(&quot;file not Deleted :&quot; + file.getPath());
                            }
                        }
                    }
                }

I tried like 4,5 different combinations but none of which seemed to work, I am trying to get the proper Path of the image, I saw that maybe using the EXTERNAL_URI would be the way to go but I don't know how to get it into my GalleryImage. Any help is appreciated!

答案1

得分: 1

public void deleteSelectedImages(){
    for(GalleryImage img : selectedImages){
        File file = new File(img.getmImageUrl());
        if(!file.exists()) {
            return;
        }

        String canonicalPath;
        ContentResolver contentResolver = getApplication().getContentResolver();
        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});
            }
        }

        images.remove(img);
    }

    imagesLiveData.setValue(images);
    selectedImages.clear();
    Toast.makeText(getApplication().getApplicationContext(), "Succesfully deleted image(s)", Toast.LENGTH_SHORT).show();
}
英文:
    public void deleteSelectedImages(){
        for(GalleryImage img : selectedImages){
            File file = new File(img.getmImageUrl());
            if(!file.exists()) {
                return;
            }

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

            images.remove(img);
        }

        imagesLiveData.setValue(images);
        selectedImages.clear();
        Toast.makeText(getApplication().getApplicationContext(), &quot;Succesfully deleted image(s)&quot;, Toast.LENGTH_SHORT).show();
    }

Hopefully it will help someone

huangapple
  • 本文由 发表于 2020年10月1日 17:26:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64152497.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定