【发布时间】:2018-08-17 12:23:33
【问题描述】:
我想根据其 URI 从设备中的图库或照片应用程序中删除图片。我在互联网上尝试了几种方法,但没有找到。
我调用了下面的方法
deleteMethod(getPath(selectedImageUri));
这两个方法的定义在这里。
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;
}
我在清单中添加权限。喜欢,
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
我的提供商看起来像:
<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>
我得到了这样的 uri:
:/storage/emulated/0/DCIM/Camera/IMG_20180804_181447.jpg
我错过了什么吗?
更新:
我在运行代码之前添加了运行时权限。在我运行代码后,它总是“file not Deleted”包含 else 块。
【问题讨论】:
-
执行代码时会发生什么?它会崩溃吗?它什么都不做吗?
-
'if (fdelete.exists()) {'文件一开始就不存在。
-
i got uri like this: :/storage/emulated/0/DCIM/Camera/IMG_20180804_181447.jpg那不是 uri。不清楚你是如何得到的。/storage/emulated/0/DCIM/Camera/IMG_20180804_181447.jpg将是一个文件系统路径。
标签: java android photos android-8.1-oreo