参照http://keeponmoving.iteye.com/blog/1515587写了一个demo,发现图片无法显示。
/*
* 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
* 这里的path是图片的地址
*/
public Uri getImageURI(String path, File cache) throws Exception {
String name = MD5.getMD5(path) + path.substring(path.lastIndexOf("."));
File file = new File(cache, name);
// 如果图片存在本地缓存目录,则不去服务器下载
if (file.exists()) {
return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
} else {
// 从网络上获取图片
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
// 返回一个URI对象
return Uri.fromFile(file);
}
}
return null;
}
} 代码读到红色字体部分的时候,跳到下面代码的catch部分。求解。
// 后台运行的子线程子线程
@Override
protected Uri doInBackground(String... params) {
try {
return service.getImageURI(params[0], cache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} 网络httpurlconnection图片
/*
* 从网络上获取图片,如果图片在本地存在的话就直接拿,如果不存在再去服务器上下载图片
* 这里的path是图片的地址
*/
public Uri getImageURI(String path, File cache) throws Exception {
String name = MD5.getMD5(path) + path.substring(path.lastIndexOf("."));
File file = new File(cache, name);
// 如果图片存在本地缓存目录,则不去服务器下载
if (file.exists()) {
return Uri.fromFile(file);//Uri.fromFile(path)这个方法能得到文件的URI
} else {
// 从网络上获取图片
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
if (conn.getResponseCode() == 200) {
InputStream is = conn.getInputStream();
FileOutputStream fos = new FileOutputStream(file);
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
is.close();
fos.close();
// 返回一个URI对象
return Uri.fromFile(file);
}
}
return null;
}
} 代码读到红色字体部分的时候,跳到下面代码的catch部分。求解。
// 后台运行的子线程子线程
@Override
protected Uri doInBackground(String... params) {
try {
return service.getImageURI(params[0], cache);
} catch (Exception e) {
e.printStackTrace();
}
return null;
} 网络httpurlconnection图片
解决方案 »
- android 4.2.1 编译到最后不能打包是怎么回事
- 如何让在wifi打开的情况下。也能使用到GPRS
- 郁闷,搭建Android平台问题,你遇到过吗?
- 关于Alarmmanager计时不准的问题
- 6成安卓应用疑泄露隐私
- 移动应用服务器端开发用的框架
- android中调用traceroute,显示到达目标IP的经过的路由器。该怎样实现
- 问一下有人知道如何获取手机话筒和喇叭的输入输出流么,谢谢
- 在SwipeRefresh刷新控件下拉时,Lis他View仍能同步下拉
- 请教问题
- 老罗将死,或者Android也将就换代,但是互联网的,共享,互助精神将永存
- 急急急!!!关于 PhoneGap onDeviceReady !
要说异常的话,可能是这句:
Type safety:Unchecked cast from Object to List<ProductInfo> (List<ProductInfo>) msg.obj