I want to delete a picture from gallery or photo apps from device according to its URI. I tried several approach around internet but no way found.
I called below method
deleteMethod(getPath(selectedImageUri));
These two method defination is here.
private void deleteMethod(String file_dj_path) {
File fdelete = new File(file_dj_path);
if (fdelete.exists()) {
if (fdelete.delete()) {
System.out.println("file Deleted :" + file_dj_path);
Toast.makeText(getApplicationContext(),
"file Deleted", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"file not Deleted", Toast.LENGTH_SHORT).show();
System.out.println("file not Deleted :" + file_dj_path);
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
//HERE YOU WILL GET A NULLPOINTER IF CURSOR IS NULL
//THIS CAN BE, IF YOU USED OI FILE MANAGER FOR PICKING THE MEDIA
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else return null;
}
I add permission in manifest. Like,
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
My provider looks like:
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path path="Android/data/com.***.calculator/"
name="files_root" />
<external-path path="." name="external_storage_root" />
</paths>
i got uri like this:
:/storage/emulated/0/DCIM/Camera/IMG_20180804_181447.jpg
Am i missing anything?
Update:
I added runtime permission before run the code. After i run the code it always goes "file not Deleted" consists else block.
You also need to check if you have the permission and if not acquire it on RUNTIME. Asking for the permissions in your manifest file is not enough. You could use these two methods to see if you have permission to write and if not acquire it: