【问题标题】:deleting an image file from the file system and then adding a new image file with the same name returns an old image when added using Uri in android从文件系统中删除图像文件然后添加具有相同名称的新图像文件在使用 android 中的 Uri 添加时返回旧图像
【发布时间】:2019-04-29 11:14:00
【问题描述】:

我正在尝试创建一个应用程序,我需要在该应用程序中同时从图像视图和外部存储中添加或删除图像。在做同样的事情时,当我尝试使用 Uri 将新图像添加到 imageview 中时,旧图像会不断被再次添加。

这是我的代码

if (resultCode == Activity.RESULT_OK && requestCode == IMAGE_PICK_CODE_GALLERY) {
            var selectedImage = data?.data
            try {
 val bitmap = MediaStore.Images.Media.getBitmap(context?.contentResolver,selectedImage)
                if(bitmap!=null) {
                    val imageURI: String = getImageUri(context!!, bitmap)
                }


private fun getImageUri(context: Context, inImage: Bitmap): String {
        var fOut: OutputStream?
        var path: String? = null
        var fileName: String? = abc
        var file: File? = null

                file = File(
                    Environment.getExternalStorageDirectory().toString() + File.separator + "myDirectory",
                    "$fileName"
                )

            if (file.exists())
            {
                file.getCanonicalFile().delete()
                if (file.exists())
                {
                    context?.deleteFile(file.getName())
                }
                file.delete()
            }
            file.createNewFile() //If file already exists will do nothing
            fOut = FileOutputStream(file)
            inImage.compress(Bitmap.CompressFormat.JPEG, 40, fOut)
            Glide.with(this).load(file).into(imageView!!)
            fOut.flush()
            fOut.close()
           // path = MediaStore.Images.Media.insertImage(context.contentResolver,file.absolutePath,file.getName(),null);
        } catch (ex: Exception) {
            ex.printStackTrace()
        }
  return file.toString()
    }

【问题讨论】:

  • 这里旧图像被添加到 imageView 但新图像被添加到外部存储中

标签: android file kotlin


【解决方案1】:

Glide 会缓存您的图像,因此您可能正在加载旧图像的缓存版本。

按照Glide's docs 中的建议,您应该添加一个签名来处理缓存失效:

Glide.with(yourFragment)
    .load(yourFileDataModel)
    .signature(new ObjectKey(yourVersionMetadata))
    .into(yourImageView);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2011-06-26
    • 1970-01-01
    • 2017-10-06
    • 1970-01-01
    相关资源
    最近更新 更多