【问题标题】:file.exists() returns false but the image uri existsfile.exists() 返回 false 但图像 uri 存在
【发布时间】:2017-07-25 05:49:42
【问题描述】:

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

我正在尝试删除在尝试获取 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);
}

然而,尽管我刚刚创建了图像 uri,但 file.exists() 返回 false。为什么会这样?

更新

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

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

我用了这个人的解决方案:Deleting files via a 'ContentResolver' as opposed to deleting them via 'file.delete()'

【问题讨论】:

  • 尝试获取绝对路径,这可能会给出路径内容://
  • selectedImage?的路径是什么
  • 你的图片路径是什么?你在File file = new File(imageUri.getPath()); 得到了什么?

标签: java android file uri


【解决方案1】:

试试这个,

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

【讨论】:

  • 谢谢!这行得通。我还有一个小问题,我将用它来更新我的原始帖子。
  • 如何将图像加载到 imageView?你在使用任何库吗?
  • 我使用 imageView.setBitmap() 方法。
猜你喜欢
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 1970-01-01
  • 2010-10-29
  • 1970-01-01
  • 2012-10-22
  • 1970-01-01
  • 2017-08-16
相关资源
最近更新 更多