android图片下载问题
============问题描述============
哪位大神帮我看看下面的代码,为什么传入Url最后得到的drawable是空呢?
// 网络图片先下载到本地cache目录保存,以imagUrl的图片文件名保存。如果有同名文件在cache目录就从本地加载
public static Drawable loadImageFromUrl(Context context, String imageUrl) {
Drawable drawable = null;
if (imageUrl == null)
return null;
String imagePath = "";
String fileName = "";
// 获取url中图片的文件名与后缀
if (imageUrl != null && imageUrl.length() != 0) {
fileName = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
}
// 图片在手机本地的存放路径,注意:fileName为空的情况
imagePath = context.getCacheDir() + "/" + fileName;
Log.i(TAG, "imagePath = " + imagePath);
File file = new File(context.getCacheDir(), fileName);// 保存文件
System.out.println("cachedir = " + context.getCacheDir());
Log.i(TAG, "file.toString()=" + file.toString());
if (!file.exists() && !file.isDirectory()) {
try {
// 可以在这里通过文件名来判断,是否本地有此图片
FileOutputStream fos = new FileOutputStream(file);
InputStream is = new URL(imageUrl).openStream();
int data = is.read();
while (data != -1) {
fos.write(data);
data = is.read();
}
fos.close();
is.close();
// drawable = Drawable.createFromStream(
// new URL(imageUrl).openStream(), file.toString() ); //
// (InputStream) new URL(imageUrl).getContent();
drawable = Drawable.createFromPath(file.toString());
Log.i(TAG, "file.exists()不文件存在,网上下载:" + drawable.toString());
} catch (IOException e) {
Log.e(TAG, e.toString() + "图片下载及保存时出现异常!");
}
} else {
drawable = Drawable.createFromPath(file.toString());
Log.i("test", "file.tostring():" + file.toString());
Log.i("test", "file.exists()文件存在,本地获取:" + drawable);
}
return drawable;
}
下面是输出:
============解决方案1============
你是不是检查了本地的/data/data/com.roy.activity/cache/test01_upload_1.jpg文件有问题?
因为网络原因下载中断或失败是很常见的事情,具体的原因要看异常里的信息。
posted on 2014-11-08 12:36 android基础教程 阅读(219) 评论(0) 收藏 举报
浙公网安备 33010602011771号