how to delete an image from android when its URI is known?

6.8k views Asked by At

Im developing an android app which selects an image from the gallery in one activity and displays it in another.But when I try to delete the selected image it doesnt delete.I'm passing its uri between the two activies. Many thanks in Advance!!!!

Here's my Code :

ACTIVITY HOMESCREEN

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);

     if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
          Uri uri = data.getData();
          Intent i = new Intent(this, Imageviewer.class);       
          i.putExtra("imgpath", uri.toString());
          startActivity(i);
     }
}

IMAGEVIEWER ACTIVITY :

Uri imageUri;
imageUri = Uri.parse(intent.getStringExtra("imgpath"));
File fdelete = new File(imageUri.toString());

    if (fdelete.exists()) {
         if (fdelete.delete()) {
               System.out.println("file Deleted :" );
         } else {
               System.out.println("file not Deleted :");
         }
    }
3

There are 3 answers

0
ʍѳђઽ૯ท On

Try this : (In the second Activity) ImageViewerActivity in your case.

Intent intent = getIntent();
        String receivedPath = intent.getExtras().getString("imgpath");
        File fdelete = new File(receivedPath);

        if (fdelete.exists()) {
            if (fdelete.delete()) {
                System.out.println("file Deleted :" );
            } else {
                System.out.println("file not Deleted :");
            }
        }

Also you can debug your codes line by line to see and check if the ImgPath is getting correctly or not!

1
Jimmy ALejandro On

With kotlin you could do: uri.toFile().delete() and its deleted

2
Axbor Axrorov On

First you must take real path of image:

//getting real path from uri
private String getFilePath(Uri uri) {
    String[] projection = {MediaStore.Images.Media.DATA};

    Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
    if (cursor != null) {
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(projection[0]);
        String picturePath = cursor.getString(columnIndex); // returns null
        cursor.close();
        return picturePath;
    }
    return null;
}

Then you can delete this file like below:

Uri imageUri;
imageUri = Uri.parse(intent.getStringExtra("imgpath"));
File fdelete = new File(getFilePath(imageUri));

if (fdelete.exists()) {
     if (fdelete.delete()) {
           System.out.println("file Deleted :" );
     } else {
           System.out.println("file not Deleted :");
     }
}