1

I've spent hours trying to figure out my problems but I just can't seem to figure out the solution.

I'm trying to delete an image that was saved when I was trying to get it's uri. The image was put in the internal storage. My code is:

Uri imageUri = getImageUri(this, selectedImage);
File file = new File(imageUri.getPath());
if (!file.exists()) {
    Log.i(TAG, "nope");
else{
    file.delete();
}
}

public Uri getImageUri(Context Context, Bitmap image) {

    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
    String path = MediaStore.Images.Media.insertImage(Context.getContentResolver(), image, "Title", null);
    Log.i(TAG, path);

    return Uri.parse(path);
}

However, file.exists() returns false despite the fact that I have just made the image uri. Why is this so?

Update

Thanks to Shinil M S I have found the solution to my problem. However I have one more issue in that whenever I delete the photo, the image is replaced with this other empty image. I have attached the picture as I'm not sure exactly what it is. How do I get rid of it completely so that the image doesn't appear at all? Image mentioned above

Update 2

I have gotten everything to work as intended.

My code is:

public static void deleteUri(Context context, Uri uri){

    long mediaId = ContentUris.parseId(uri);
    Uri contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Uri itemUri = ContentUris.withAppendedId(contentUri, mediaId);

    context.getContentResolver().delete(itemUri, null, null);
}

I used this person's solution: Deleting files via a 'ContentResolver' as opposed to deleting them via 'file.delete()'

tokenturtle
  • 21
  • 1
  • 5

1 Answers1

0

try this,

Uri imageUri = getImageUri(this, selectedImage);
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = context.getContentResolver().query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();

File file = new File(filePath);
if (!file.exists()) 
  Log.i(TAG, "nope");
else 
  file.delete();
shinilms
  • 1,494
  • 3
  • 22
  • 35