当前位置: 代码迷 >> Android >> android图片下载有关问题
  详细解决方案

android图片下载有关问题

热度:96   发布时间:2016-04-28 04:06:05.0
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;
}


下面是输出:
------解决思路----------------------
引用:
Quote: 引用:

Quote: 引用:

Quote: 引用:

你的问题是这么产生的:
1.第一次调用函数,因为在本地不存在,所以去网络下载。
2.因为你在UI线程中访问网络,所以导致异常,并在本地生成一个长度为0的空文件。
3.第二次调用函数,因为本地文件存在,所以执行的是else分支
4.因为文件内容为空,所以Drawable.createFromPath返回null

解决方法:
1.不要在UI线程中下载文件。
2.下载文件发生异常时删除残留文件。
可问题是我并没有在UI线程里下载啊,logcat里也没有报exception,我是在线程池里调用上面的方法的。如下:

executor = new ThreadPoolExecutor(1, 50, 180, TimeUnit.SECONDS, queue);

// 用线程池来做下载图片的任务
executor.execute(new Runnable() {
@Override
public void run() {
Drawable drawable = loadImageFromUrl(context, imageUrl);
imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}
});


那可能是下载失败导致本地文件内容不完整导致的。你可以检查一下/data/data/com.roy.activity/cache/test01_upload_1.jpg
这个文件。
下载失败的原因是什么?我该怎么做才能让图片正确显示呢?

你是不是检查了本地的/data/data/com.roy.activity/cache/test01_upload_1.jpg文件有问题?
因为网络原因下载中断或失败是很常见的事情,具体的原因要看异常里的信息。
  相关解决方案