【发布时间】:2018-01-11 09:55:09
【问题描述】:
我在一个 recyclerview 中有项目,当我使用 HttpURLConnection 库下载它并保存具有图像的项目时,它会正确保存在我的手机中。 当我在我的应用程序中从手机中删除该项目时,它将正确删除描述和图像
如果我用另一个图像保存该项目,但图像的名称相同,我看到它显示了我之前保存的第一张图像,即使在我删除它之后也是如此。
我没有缓存图像的代码,但我有清理缓存文件夹的代码 我已经测试了该代码并清除了缓存文件夹,但我还遇到了这个问题。 在调试中我看到缓存文件夹是空的,因为“for”没有运行,直接删除了缓存文件夹
除了缓存文件夹之外还有其他文件夹可以让我的 android 保存图像进行缓存吗?
下载图片代码:
private Bitmap downloadUrl(String strUrl) throws IOException {
Bitmap bitmap = null;
InputStream iStream = null;
File secondFile;
Bitmap.CompressFormat format = null;
try {
File myDir = AdapterContext.getFilesDir();
String Extention ="png"
File NewsDirectory = new File("my app location and folder");
if (!(NewsDirectory.isDirectory() && NewsDirectory.isDirectory())) {
boolean success = (new File("check if folder is not made then it make it")).mkdir();
}
URL url = new URL(strUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(iStream);
secondFile = new File("my app folder"+"my file name" + Extention);
ImageAddress = secondFile.toString();
FileOutputStream stream = new FileOutputStream(secondFile);
ByteArrayOutputStream outstream = new ByteArrayOutputStream();
format = Bitmap.CompressFormat.PNG;
bitmap.compress(format, 85, outstream);
byte[] byteArray = outstream.toByteArray();
stream.write(byteArray);
stream.close();
ImageDownloaded = true;
} catch (Exception e) {
} finally {
iStream.close();
}
return bitmap;
}
删除缓存代码:
File dir = Context.getCacheDir();
deleteDir(dir);
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
return dir.delete();
} else if(dir!= null && dir.isFile()) {
return dir.delete();
} else {
return false;
}
}
【问题讨论】:
标签: android image caching download