file.exists() 返回 false,但图像 uri 存在



我花了几个小时试图找出我的问题,但我似乎无法找出解决方案。

我正在尝试删除在尝试获取其 uri 时保存的图像。图像被放入内部存储中。 我的代码是:

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);
}

但是,file.exists(( 返回 false,尽管我刚刚制作了图像 uri。为什么会这样?

更新

感谢Shinil M S,我找到了解决问题的方法。但是,我还有一个问题,即每当我删除照片时,图像都会替换为另一个空图像。我附上了图片,因为我不确定它到底是什么。如何完全摆脱它,以便图像根本不出现?上面提到的图像

更新 2

我已经让一切都按预期工作。

我的代码是:

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);
}

我使用了这个人的解决方案:通过"内容解析器"删除文件,而不是通过"file.delete(("删除它们

试试这个,

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();

最新更新