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<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;
}
}
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("file Deleted :" + file.getPath());
} else {
System.out.println("file not Deleted :" + 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!
Hopefully it will help someone